将匹配的单词替换为PHP字符串中的数字/数字


Replace matching word with a digit/number in a string in PHP

我想用数字/数字替换字符串中的某些单词,只有当该单词后面或前面有数字[中间允许有空格]时。例如,这里有一个示例字符串,我希望将中的替换为2,并将中的替换为4。我已经尝试过str_replace,但不能满足全部目的,因为它替换了字符串中的所有中的

$str = 'Please wait for sometime too, the area code is for 18 and phone number is too 5897 for';
$str = str_ireplace(' for ', '4', $str);
$str = str_ireplace(' too ', '2', $str);
echo $str;

,但它没有给我期望的输出,这应该是也请稍等,区号是418,电话是258974

这可能有点太长了,但是你明白了:

http://3v4l.org/JfXBN

<?php
$str="Please wait for sometime too, the area code is for 18 and phone number is too 5897 for";
$str=preg_replace('#('d)'s*for#','${1}4',$str);
$str=preg_replace('#('d)'s*too#','${1}2',$str);
$str=preg_replace('#for's*('d)#','4${1}',$str);
$str=preg_replace('#too's*('d)#','2${1}',$str);
echo $str;

输出:

请稍等,区号是418,电话是258974

警告:

如果你的字符串看起来像这样:8 too for
这个代码片段可能会失败,也可能不会失败,这取决于您期望的是824还是82 for,因为它不进行递归替换(当前序列返回82 for)。

您应该使用preg_replace_callback():

$str = preg_replace_callback('~'d'K'h*(?:too|for)|(?:too|for)'h*(?='d)~i', 
     function($m) {
        return strtr(strtolower(trim($m[0])), array('too'=>2,'for'=>4));
     }, $str);