Fatih Yavuz Fatih Yavuz - 4 months ago 16
PHP Question

How to put matched part into end of the string?

I'm trying to figure out how to put matched part of a string to the end of the string in php.

For example, let's say that we have string like this:

"<span>Foo</span> rest of the string"

At final, I'd like to obtain this:

"rest of the string Foo"


$string = "<span>Foo</span> rest of the string";
//$str = preg_replace("/<span>(.*?)<\/span>/","$1",$string);

I know that matched part is represented by $1 but I could not find a way to put it to the end.


$1 refers to the first captured group (a capture group is marked by a pair of parantheses) Now you just need to capture the rest of the string in another group ($2) and then put it in the replaced pattern like so:
$str = preg_replace("/<span>(.*?)<\/span>\s*(.*)/","$2 $1",$string);