如何只用preg_replace替换字符串的最后一个匹配项? [英] How to replace only the last match of a string with preg_replace?

查看:410
本文介绍了如何只用preg_replace替换字符串的最后一个匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须替换HTML文档中字符串(例如foo)的最后一个匹配项.问题在于HTML文档的结构始终是随机的.

I have to replace the last match of a string (for example the word foo) in HTML document. The problem is that the structure of the HTML document is always random.

我正在尝试使用preg_replace来实现,但是到目前为止,我知道如何仅替换第一个匹配项,而不替换最后一个匹配项.

I'm trying to accomplish that with preg_replace, but so far I know how to replace only the first match, but not the last one.

谢谢.

推荐答案

(?!...)

$str = 'text abcd text text efgh';
echo preg_replace('~text(?!.*text)~', 'bar', $str),"\n";

输出:

text abcd text bar efgh

这篇关于如何只用preg_replace替换字符串的最后一个匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆