How to use backreferences in PHP
-
11-10-2019 - |
Question
I want to add a character to the end of each file extension found in a body of text using preg_replace().
Here is some sample text:
$string='http://www.mysite.com/expert/images/imageone.jpghttp://www.mysite.com/expert/images/imagetwo.jpg';
This search & replace works fine in TextWrangler, appending a semi colon to file extensions:
(\.(jpg|gif|html?|php|tiff?|pdf|png))
\1;
Translated to PHP, however does not work, having no effect; no errors.
preg_replace("/(\.(jpg|gif|html|php|tif|tiff|pdf|htm|png))/","\\1;",$string);
Solution
It works perfectly for me, but you should try using $1
:
$string = preg_replace("/.../","$1;",$string);
or put the replacement in single quotes:
$string = preg_replace("/.../",'\\1;',$string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow