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

用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

  • 写回答

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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)