如何在PHP中使用反向引用

时间:2011-01-14 17:47:51

标签: php preg-replace backreference

我想使用preg_replace()在文本正文中找到每个文件扩展名的末尾添加一个字符。

以下是一些示例文本:

$string='http://www.mysite.com/expert/images/imageone.jpghttp://www.mysite.com/expert/images/imagetwo.jpg';

此搜索&替换在TextWrangler中工作正常,将半冒号附加到文件扩展名:

(\.(jpg|gif|html?|php|tiff?|pdf|png))


\1;

转换为PHP但是不起作用,没有效果;没有错误。

preg_replace("/(\.(jpg|gif|html|php|tif|tiff|pdf|htm|png))/","\\1;",$string);

1 个答案:

答案 0 :(得分:3)

它非常适合我,但您应该尝试使用$1

$string = preg_replace("/.../","$1;",$string);

或将替换单引号:

$string = preg_replace("/.../",'\\1;',$string);