0

Let's assume I use the following php function:

 preg_replace($search, $replace, $str);

I'm only able to modify the search and replace var. Is it possible to do the following replace:

test -> test test2

And

test 3 -> test3

I tried the following:

$search = '/test (?=*)/';
$replace = 'test($1)';

This works for the second case. But now I want to use a if, in order to say "if $1 is empty, add test2. But I'm only able to modify the search and replace var without using addition php. Is this even possible in regex?

4

2 に答える 2

2

検索および置換パラメーターを配列として渡すことができます。したがって、検索クエリの配列を検索パラメーターに渡し、対応する置換文字列の配列を置換パラメーターに渡します...

だから、あなたは試すかもしれません:

$search = array('/test(\s?)$/','/test (?=*)/');
$replace = array('test test2','test($1)');
preg_replace($search, $replace, $str);
于 2012-12-11T09:00:34.757 に答える
0

私はあなたの仕事のためにあなたが正規表現を使うべきではないと思います。この場合、str_replaceと2つの配列を使用できます-検索と変更に

$str = str_replace(array("test", "test 3"), array("test test2", "test3"), $str);
于 2012-12-11T09:02:40.683 に答える