如何在整个网站范围内替换单词?

时间:2019-02-19 14:33:10

标签: php wordpress function

目标是替换(WordPress)网站中整个文章中的单词。我已经尝试过下面的代码,并且可以正常工作,但是我希望能够限制它的作用。我只想在每个帖子上替换单词的第一个实例(当前它当然会替换所有实例)。主要目的是创建站点范围的链接。

function link_words( $text ) {
    $replace = array(
        'google' => '<a href="http://www.google.com">Google</a>',
        'computer' => '<a href="http://www.myreferral.com">computer</a>',
        'keyboard' => '<a href="http://www.myreferral.com/keyboard">keyboard</a>'
    );
    $text = str_replace( array_keys($replace), $replace, $text );
    return $text;
}
add_filter( 'the_content', 'link_words' );
add_filter( 'the_excerpt', 'link_words' );

(《第一网站指南https://firstsiteguide.com/search-and-replace-wordpress-text/中Ivan Juristic的代码感谢)

编辑:正如下面的堆栈器已经指出的那样,存在一个问题,该代码可能会无意间编辑链接并将其断开。另外,我确实发现该代码中断了链接到其中包含单词的图片的链接。因此,我也想知道如何仅将其应用于帖子段落中的单词,而不应用于其他html。

1 个答案:

答案 0 :(得分:0)

您可能想看看strpos()substr_replace()的组合。首先,通过strpos()获取帖子中第一个出现的位置,然后用substr_replace()替换该出现:

function link_words( $text ) {
    $replace = array(
        'google' => '<a href="http://www.google.com">Google</a>',
        'computer' => '<a href="http://www.myreferral.com">computer</a>',
        'keyboard' => '<a href="http://www.myreferral.com/keyboard">keyboard</a>'
    );
    foreach ($replace as $key => $singleReplacement) {
        $start = strpos($text, $key);
        if ($start !== false) {
            $text = substr_replace($key, $singleReplacement,$start, strlen($key));
        }
    }
    return $text;
}
相关问题