0

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"

Code:

$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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
delinane
  • 135
  • 1
  • 15

1 Answers1

0

$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);

Phu Ngo
  • 866
  • 11
  • 21
  • I've tried the following code before I asked the question which did not work. Thanks to your answer, I realized that it is because of the question mark I put at the end of the pattern. Can you explain why? `$string = "Foo rest of the string"; $str = preg_replace("/(.*?)<\/span>(.*?)/","$2 $1",$string);` – delinane Aug 21 '16 at 13:46
  • Normal `*` without modifying flag is greedy match and will try to consume as much as possible. `*?` is lazy match and only matches more when backtracked. See more: http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions – Phu Ngo Aug 21 '16 at 13:52
  • And so in your code it will only replace the part `Foo␣` of the string, capturing `␣` as the 2nd group, and swap only that single space up in front of `Foo` – Phu Ngo Aug 21 '16 at 13:56