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?

2
  • $replace = 'test(${1})'; Commented Dec 11, 2012 at 8:56
  • Is there a space after the first "test"? Commented Dec 11, 2012 at 8:59

2 Answers 2

3

You can pass the search and replace parameters as arrays. So pass an array of search queries into the search parameter, and an array of corresponding replace strings in the replace parameter...

so, you might try:

$search = array('/test(\s?)$/','/test (?=*)/');
$replace = array('test test2','test($1)');
preg_replace($search, $replace, $str);
Sign up to request clarification or add additional context in comments.

Comments

0

I think for you task you should't use regexp. For this case you can use str_replace and two arrays - for search and for change

$str = str_replace(array("test", "test 3"), array("test test2", "test3"), $str);

1 Comment

Won't the first element ("test") prevent the second element from working? Not to spec!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.