Php取代确切的单词

时间:2012-11-01 10:04:33

标签: php regex preg-replace

这是我的问题:

使用preg_replace('@\b(word)\b@','****',$text);

我在word\word and word的文字中,上面的preg_replace替换了word\wordword,因此我的结果字符串为***\word and ***

我希望我的字符串看起来像:word\word and ***

这可能吗?我做错了什么???

稍后编辑

我有一个带url的数组,我预先知道那个数组并preg_replace找到url的文本,但是它没有用。

例如,我有http://www.link.comhttp://www.link.com/something

如果我http://www.link.com,它还会替换http://www.link.com/something

3 个答案:

答案 0 :(得分:3)

您有效地指定您不希望某些字符计为字边界。因此,您需要自己指定“边界”,如下所示:

preg_replace('@(^|[^\w\\])(word)([^\w\\]|$)@','**',$text);

这样做的目的是搜索除了反斜杠\以外的行边界或非单词字符所包围的单词。因此它将匹配 .word,但不匹配 .word \ 而不是 \ word。如果您需要从匹配中排除其他字符,只需将它们添加到括号内。

答案 1 :(得分:0)

您可以使用str_replace("word\word", "word\word and"),我真的不明白为什么您需要在上面给出的情况下使用preg_replace。

答案 2 :(得分:0)

这是一个不使用正则表达式的简单解决方案。它只会取代单词出现的单词'这是一个单词。

<?php
$text = "word\word word cat dog";
$new_text = "";
$words = explode(" ",$text); // split the string into seperate 'words'

$inc = 0; // loop counter
foreach($words as $word){

    if($word == "word"){ // if the current word in the array of words matches the criteria, replace it
        $words[$inc] = "***";
    }
    $new_text.= $words[$inc]." ";
    $inc ++;
}

echo $new_text; // gives 'word\word *** cat dog'
?>
相关问题