doupang9614
2015-08-09 02:59
浏览 170
已采纳

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

I want to replace some words in a string with a digit/number only if that word is followed or preceded by a digit [whitespace(s) allowed in between]. For example, here is an example string in which I wish to replace too with 2 and for with 4. I have tried with str_replace, but doesn't serve the full purpose as it replaces all for and too in the string

$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;

but it isn't giving me the desired output which should be Please wait for sometime too, the area code is 418 and phone number is 258974

图片转代码服务由CSDN问答提供 功能建议

我想用字母/数字替换字符串中的某些单词,只有当该单词后跟或前面有 数字[中间允许的空格]。 例如,下面是一个示例字符串,我希望将替换为2,将替换为替换为4.我已尝试使用str_replace,但不能完全满足目的 因为它取代了字符串中所有 <前> $ str ='请等待一段时间,该区域 代码是18,电话号码是5897 for'; $ str = str_ireplace('for','4',$ str); $ str = str_ireplace('too','2',$ str) ; echo $ str;

但它没有给我所需的输出,应该是 请等一段时间,区号 是418,电话号码是258974

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzan9069 2015-08-09 03:35
    已采纳

    This may be a little too long, but you get the idea:

    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;
    

    Outputs:

    Please wait for sometime too, the area code is 418 and phone number is 258974

    Warning:

    If your string looks like this: 8 too for,
    this code snippet may or may not fail depending on whether you expect 824 or 82 for, since it does not do recursive replace (the current sequence returns 82 for).

    打赏 评论
  • dongna9185 2015-08-09 03:41

    You should be using preg_replace_callback() for this:

    $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);
    
    打赏 评论

相关推荐 更多相似问题