如何在PHP中替换字符串中的单个单词


How to replace individual words in a string in PHP?

我需要用数组给出的替代品替换单词

$words = array(
'one' => 1,
'two' => 2,
'three' => 3
);
$str = 'One: This is one and two and someone three.';
$result = str_ireplace(array_keys($words), array_values($words), $str);

,但该方法将someone改为some1。我需要替换单个单词

您可以在正则表达式中使用单词边界来要求单词匹配。

类似:

'bone'b

会这样做。preg_replacei修饰符是你想在PHP中使用的。

Regex demo: https://regex101.com/r/GUxTWB/1

PHP使用方法:

$words = array(
'/'bone'b/i' => 1,
'/'btwo'b/i' => 2,
'/'bthree'b/i' => 3
);
$str = 'One: This is one and two and someone three.';
echo preg_replace(array_keys($words), array_values($words), $str);
PHP Demo: https://eval.in/667239 输出:

1:这是1和2和某人3。

可以使用'b作为preg_replace:

中的词边界
foreach ($words as $k=>$v) {
  $str = preg_replace("/'b$k'b/i", $v, $str);
}

这个函数将帮助您替换PHP中的一些单词,而不是字符。它使用prereplace()函数

<?PHP
      function removePrepositions($text){
            
            $propositions=array('/'bthe'b/i','/'bor'b/i', '/'ba'b/i', '/'band'b/i', '/'babout'b/i', '/'babove'b/i'); 
        
            if( count($propositions) > 0 ) {
                foreach($propositions as $exceptionPhrase) {
                    $text = preg_replace($exceptionPhrase, '', trim($text));
                }
            $retval = trim($text);
            }
        return $retval;
    }
            
?>