簡體   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