1

When using preg_replace with repeating pattern, the reference just return the last one. Is there any way to get all?

for example:

 $str = "hello, world, hello1, world1"
 echo(preg_replace('/([^,]*,?)+/', '$1', $str));

would return world1, but is there any way to access to other matched part?

This is just an example, I just want to know if there is any way to access all matched part in reference?

11
  • This is an example, not the real case. Commented Aug 5, 2012 at 11:44
  • Can you post the real case, then? Otherwise, our solutions may not work as you expect. Commented Aug 5, 2012 at 11:46
  • I asked that in another question, got no answer! stackoverflow.com/questions/11815843/… Commented Aug 5, 2012 at 11:47
  • 1
    perhaps you could take a look at preg_replace_callback Commented Aug 5, 2012 at 11:49
  • preg_replace_callback works the same way, no access to repeating part!!! Commented Aug 5, 2012 at 11:51

1 Answer 1

2

As an aside, I went to test my examples, and found that yours doesn't actually work. It needs to be [^,]+ not [^,]* otherwise it eats the input:

$str = "hello, world, hello1, world1"
echo preg_replace('/([^,]*,?)+/', '$1', $str);
# -> ""
echo preg_replace('/([^,]+,?)+/', '$1', $str);
# -> " world1"

You could capture all occurrences, by adding another set of brackets:

$str = "hello, world, hello1, world1"
echo preg_replace('/(([^,]+,?)+)/', '$1', $str);
# -> "hello, world, hello1, world1"

Or you could replace each individual occurrence, rather than the whole repeating pattern:

$str = "hello, world, hello1, world1"
echo preg_replace('/([^,]+,?)/', '$1 AND', $str);
# -> "hello, AND world, AND hello1, AND world1 AND"

If neither of those is what you want, then I suspect preg_replace is not what you want, and preg_match_all might be more appropriate.

Sign up to request clarification or add additional context in comments.

Comments

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.