Ali
Ali

Reputation: 22317

preg_replace with repeating pattern

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?

Upvotes: 1

Views: 1937

Answers (1)

IMSoP
IMSoP

Reputation: 97688

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.

Upvotes: 2

Related Questions