如何仅替换 <p> 标签中的单词?
How to replace a word only in a <p>-tag?
如何只替换 <p>
-Tag 中的单词,而不是 <h3>
或 <p class="no-change">
-Tag 中的内容?
我想改变这个:
<p>My Text and an Old Word and more </p>
在
<p>My Text and an New Word and more </p>
我试过这个:
function changer($content){
$word = str_replace('Old Word', 'New Word', $content);
$content = preg_replace('/<h3>(.*?)<\/h3>/im', $word, $content);
return $content;
}
add_filter('the_content','changer');
但是我得到了双重结果...
您得到双重结果是因为:
$word = str_replace( 'Old Word', 'New Word', $content );
$word
是 $content
的完整 Old Word
替换为 New Word
。然后用 preg_replace
中的 $word
替换,这样找到的位被替换为完整的 $content
减去已经被替换的 Old Word
。
每更新一种方法:
$html = '<p>My Text and an Old Word and more </p>
<p>My Text and an Old2 Word and more </p>
<p>My Text and an Old3 Word and more </p>
<h3>My Text and an Old Word and more </h3>';
$html = preg_replace_callback('~<p>(.*?)</p>~', function ($p_content) {
return str_replace('Old Word', 'New Word', $p_content[1]);
}, $html);
echo $html;
您还可以使用解析器并遍历所有 p
元素以查看它们是否包含 Old Word
.
如何只替换 <p>
-Tag 中的单词,而不是 <h3>
或 <p class="no-change">
-Tag 中的内容?
我想改变这个:
<p>My Text and an Old Word and more </p>
在
<p>My Text and an New Word and more </p>
我试过这个:
function changer($content){
$word = str_replace('Old Word', 'New Word', $content);
$content = preg_replace('/<h3>(.*?)<\/h3>/im', $word, $content);
return $content;
}
add_filter('the_content','changer');
但是我得到了双重结果...
您得到双重结果是因为:
$word = str_replace( 'Old Word', 'New Word', $content );
$word
是 $content
的完整 Old Word
替换为 New Word
。然后用 preg_replace
中的 $word
替换,这样找到的位被替换为完整的 $content
减去已经被替换的 Old Word
。
每更新一种方法:
$html = '<p>My Text and an Old Word and more </p>
<p>My Text and an Old2 Word and more </p>
<p>My Text and an Old3 Word and more </p>
<h3>My Text and an Old Word and more </h3>';
$html = preg_replace_callback('~<p>(.*?)</p>~', function ($p_content) {
return str_replace('Old Word', 'New Word', $p_content[1]);
}, $html);
echo $html;
您还可以使用解析器并遍历所有 p
元素以查看它们是否包含 Old Word
.