在str_replace中排除html属性

时间:2017-06-07 10:15:37

标签: php wordpress replace str-replace

所以我试图通常在wordpress中替换公司名称的每个实例,并且我偶尔会遇到一个问题(通常在链接的href中)打破链接。

代码我正在使用(包括ACF自定义字段的过滤器)

    //Replace the word lunch with a span
function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'lunch!' => '<span class="lunch">lunch!</span>',
        'Lunch!' => '<span class="lunch">lunch!</span>',
        'LUNCH!' => '<span class="lunch">lunch!</span>'
    );
    $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');
add_filter('acf_the_content', 'replace_text_wps');

有没有办法只在href标签之类的东西之外替换它?我已经研究过像DOM解析这样的东西,但我不确定是否有更简单的方法 - 它似乎不会导致任何其他情况下的悲伤,所以我不确定pre =处理整个HMTL并寻找单词是合适的。我确实想知道在它之前和之后搜索包含空格的字符串,但是我不确定如何包含前导/尾随空格,它感觉有点大杂烩? 提前致谢! 皮特

1 个答案:

答案 0 :(得分:1)

好的,所以在这个非常具体的实例中,我发现以下代码运行良好。在初始匹配参数中添加了尾随/前导空格,以及在包含空格的html标记之后直接找到它的变体。 不太优雅,但足以达到此目的。

function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' Lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' LUNCH! ' => ' <span class="lunch">lunch!</span> ',
        // used at end of lines
        ' lunch!' => ' <span class="lunch">lunch!</span>',
        ' Lunch!' => ' <span class="lunch">lunch!</span>',
        ' LUNCH!' => ' <span class="lunch">lunch!</span>',
        // used inside html tags like headers
        '>lunch!' => '><span class="lunch">lunch!</span>',
        '>Lunch!' => '><span class="lunch">lunch!</span>',
        '>LUNCH!' => '><span class="lunch">lunch!</span>',
        //used directly after html tags
        '> lunch!' => '> <span class="lunch">lunch!</span>',
        '> Lunch!' => '> <span class="lunch">lunch!</span>',
        '> LUNCH!' => '> <span class="lunch">lunch!</span>',
        //exclude alt tags on images, title attributes etc
        '"lunch!' => '"lunch!',
        'lunch!"' => 'lunch!"',
        '"Lunch!' => '"lunch!',
        'Lunch!"' => 'lunch!"'
    );
    $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');
add_filter('acf_the_content', 'replace_text_wps');