如何更改字符串中第一次出現的單詞?如何更改字符串中第一次出現的單詞
實施例:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
到
$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
如何更改字符串中第一次出現的單詞?如何更改字符串中第一次出現的單詞
實施例:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
到
$b = "Yo! **Welcome** this is the first word of Hello in this sentence";
這個工作,雖然有點低效:
$a = "Yo! **Hello** this is the first word of Hello in this sentence";
$a = preg_replace('/Hello/', 'Welcome', $a, 1);
其他流行的答案是:
$b = str_replace('Hello', 'Welcome', $a, 1);
不起作用。 str_replace
的第四個參數應該是一個變量,它通過引用傳遞,並且str_replace
將它設置爲替換的數量爲。
更好的解決方案將是,以提取從輸入字符串的兩個子串:
Hello
第一次出現之前,把它的第一次出現之後$s1
Hello
,稱之爲$s2
人們可以使用strpos
得到的位置。
結果是$s1.'Welcome'.$s2
構建:
function str_replace_first($search, $replace, $source) {
$explode = explode($search, $source);
$shift = array_shift($explode);
$implode = implode($search, $explode);
return $shift.$replace.$implode;
}
稱之爲:
$msg = "Yo! **Hello** this is the first word of Hello in this sentence";
echo str_replace_first('Hello', 'Welcome', $msg);
試試看:
http://sandbox.onlinephpfunctions.com/code/399ec70333832423c79d36a42032124d5c296d27
這是最好的緊湊性和表演:「如果獲得通過,這將被設置爲替換數:
if(($offset=strpos($string,$replaced))!==false){
$string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}
沒有正則表達式
第一個解決方案,實際工作;) – str
剛剛看到你的編輯 - 我已經實現你的第二個解決方案,並張貼它作爲答案:) – nickb
*看到效率低下的答案* ...在生產代碼中使用它。爲什麼?比第二個建議的解決方案更容易理解:) – Dennis