本文介紹了php從第0個位置替換第一次出現(xiàn)的字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想在 php 中搜索并替換第一個單詞,如下所示:
I want to search and replace the first word with another in php like as follows:
$str="nothing inside";
在不使用substr
輸出應該是:'里面的東西'
output should be: 'something inside'
推薦答案
使用 preg_replace()
限制為 1:
Use preg_replace()
with a limit of 1:
preg_replace('/nothing/', 'something', $str, 1);
用您要搜索的任何字符串替換正則表達式 /nothing/
.由于正則表達式總是從左到右計算,這將始終匹配第一個實例.
Replace the regular expression /nothing/
with whatever string you want to search for. Since regular expressions are always evaluated left-to-right, this will always match the first instance.
這篇關(guān)于php從第0個位置替換第一次出現(xiàn)的字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!