如何替换 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。我需要替换个别单词。

您可以在 preg_replace 中使用 \b 作为单词边界:

foreach ($words as $k=>$v) {
  $str = preg_replace("/\b$k\b/i", $v, $str);
}

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

类似于:

\bone\b

会做的。 preg_replace with the i modifier 是您想要在 PHP 中使用的内容。

正则表达式演示: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 演示:https://eval.in/667239

输出:

1: This is 1 and 2 and someone 3.

此功能将帮助您替换 PHP 中的一些单词,但不是字符。它使用 pre-replace() 函数

<?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;
    }

?>

whole example