PHP正则表达式找到单词(即使是双字母)然后替换它

时间:2015-09-25 14:50:00

标签: php regex string preg-replace str-replace

我使用PHP创建字符串过滤器。我需要用其他单词替换一些单词,所以我使用str_replace()函数,如下所示:

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// echo -> "You should eat pizza, beer, and ice cream every day.";

到目前为止这么好但是我需要替换单词,即使它们包含这样的几个字母:

$phrase  = "You should eat fruuits, vegetaaables, and fiiibeeer every day.";

我发现这个例子删除字符串中的双字母:

$string = preg_replace('/(\w)\1+/', '$1', $phrase);

但是,如果我将此示例应用于我的字符串,则所有带双字母的单词都将被更改...例如" Google"将成为" Gogle"我不想要那个。

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:1)

我做这样的事情

$phrase  = "You should eat suck, sck, and suuucky every day.";
$healthy = 's+u*c+k+';
$yummy = 'luck';
$newphrase = preg_replace('/' . $healthy . '/', $yummy, $phrase);
echo $newphrase;

输出:

You should eat luck, luck, and lucky every day.

+是量词,表示前一个字符中的一个或多个。 *是一个零或更多的量词,意味着角色不必存在但是如果它可以存在任何数量的那个角色。

演示:https://regex101.com/r/sN5sZ6/1

同样应使用ass字边界,因为您不想替换class等等。https://regex101.com/r/oM4wY1/2有点成为一条蜿蜒的道路..

答案 1 :(得分:0)

如果您需要特定字词,则可以在preg_replace中使用多种模式。

对于您的示例,您可以使用多种模式:

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$patterns = array("/fru+its/", "/vegeta+bles/", "/fi+be+r/");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = preg_replace($patterns, $yummy, $phrase);

如果您只想检测fruitsvegetablesfiber,则可以使用:

$patterns = array("f+r+u+i+t+s+", "v+e+g+e+t+a+b+l+e+s+", "f+i+b+e+r+");

<强> Regex demo

<强> IdeOne code example

答案 2 :(得分:0)

工作示例

$word =array('fiber', 'milk', 'nuts'); // words to scan for
$phrase = "You should eat fibeeer, nuuuuts, and milkkk every day."; //phrase
$filter = array(); // array of dynamicly generated filters

foreach($word as $name){ // loop for filter generating
    $temp = str_split($name);
    $temp = implode('{1,}', $temp). '{1,}';
    $filter[$name] = $temp;
}


$phraseTable = explode(' ', $phrase); // getting phrase into an array

foreach($phraseTable as &$data){ // scanning phrase
    foreach($filter as $name => $value){
         if(  preg_match( '/'.$value.'[,.]?/', $data)){
             $data = $name;
    }  
    } 
}       

$phraseScanned = implode(' ', $phraseTable); // imploding formatted phrase
echo $phraseScanned;  // echo result