我需要用数组给出的替换词替换单词
$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
。我需要替换单个单词。
答案 0 :(得分:5)
您可以在正则表达式中使用word boundries来要求单词匹配。
类似的东西:
\bone\b
会这样做。使用preg_replace
修饰符的i
是您希望在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:这是1和2,有人3。
答案 1 :(得分:2)
您可以在preg_replace中使用\ b作为单词边界:
foreach ($words as $k=>$v) {
$str = preg_replace("/\b$k\b/i", $v, $str);
}
答案 2 :(得分:0)
此函数将帮助您替换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;
}
?>