gpt4 book ai didi

php - 除非在 HTML 标记中找到,否则如何使用 PHP 搜索和替换匹配的文本?

转载 作者:行者123 更新时间:2023-11-28 00:15:21 25 4
gpt4 key购买 nike

如何搜索和替换所有出现的单词或短语的字符串,除非它位于 HTML 标记内?

目前有这个:

<?php
public function add_acronyms($content){
if(strpos($content, get_bloginfo('description')) !== false){
$content = str_replace(get_bloginfo('description'), '<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', $content);
if(strpos($content, '="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>') !== false){
$content = str_replace('="<acronym title="'.get_bloginfo('name').'">'.get_bloginfo('description').'</acronym>', get_bloginfo('description'), $content);
}
}
return $content;
}
?>

但这只有在 HTML 属性的开头找到单词或短语时才有效。

最佳答案

在寻找类似的东西时发现了这个。我的回答不是实现它的最优雅的方式,但它可能对您有所帮助 - 我的问题和答案在这里 - 但是如前所述,几乎肯定有更好的方法来实现这一点在我的例子中,试图替换一个词会破坏一些 href 标签,所以我使用了以下代码(顺便说一下,这是在 Wordpress 中)

function replace_text_wps($text){
$replace = array(
// used mid-line
' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
' YOUR_TEXT ' => ' <span class="YOUR_CLASS">YOUR_TEXT</span> ',
// used at end of lines
' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
' YOUR_TEXT' => ' <span class="YOUR_CLASS">YOUR_TEXT</span>',
// used inside html tags like headers
'>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
'>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
'>YOUR_TEXT' => '><span class="YOUR_CLASS">YOUR_TEXT</span>',
//used directly after html tags
'> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
'> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
'> YOUR_TEXT' => '> <span class="YOUR_CLASS">YOUR_TEXT</span>',
//exclude alt tags on images, title attributes etc
'"YOUR_TEXT' => '"YOUR_TEXT',
'YOUR_TEXT"' => 'YOUR_TEXT"',
'"YOUR_TEXT' => '"YOUR_TEXT',
'YOUR_TEXT"' => 'YOUR_TEXT"'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');

exclude html attributes in str_replace

关于php - 除非在 HTML 标记中找到,否则如何使用 PHP 搜索和替换匹配的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com