繁体   English   中英

用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM