使用REGEX(PHP代码)替换两个HTML标签之间的所有“foo”


replace all "foo" between two HTML tags using REGEX (PHP code)

我想要一个正则表达式代码,将所有"foo"字符串替换为"bar",在html标签pre>

这是一个例子:

< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>

应该成为

< html>
< p> blah blah blah foo try foo< /p>
< pre> bar try bar word barbar < /pre>
< /html>

所以,这意味着标签之间的所有foo都应该替换为。

我尝试使用这种正则表达式模式,但它不起作用。

do {
$string = preg_replace('/< pre>([^)]*)foo([^)]*< /pre>)/U', ''1boo'2', $string, -1,$count);
}while($count != 0);
echo $string;

我很抱歉我的英语谢谢

$string = '< html>
< p> blah blah blah foo try foo< /p>
< pre> foo try foo word foofoo < /pre>
< /html>';
$string = preg_replace('/foo(?=(?:.(?!< pre>))*< '/pre>)/Um', 'boo', $string);
echo $string;
您可以使用

DOMDocument 提取 HTML 标记的文本内容,对文本进行简单的str_replace并更新 DOM。

首先,去获取Simple HTML Dom

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find the first pre (you can change this or find an array based on documentation on website to suit your needs, but I will make it just for the first pre for now
$html->find('pre', 0)->plaintext = str_replace('foo', 'bar', $html->find('pre', 0)->plaintext);
//Echo HTML
echo $html;