2017-05-10 295 views
-2

如何替換PHP只有第一個字和第二個字而不是替換第三個字?如何只替換PHP的第一個字和第二個字而不是替換第三個字?

$test = "hello i love animal love dog and and love tree"; 

我想更換最前一頁和secode字loveunderscore,而不是取代第三字love這樣。

hello i _ animal _ dog and and love tree 

然後,我用這個代碼

$test = str_replace('love', '_', $test); 
echo $test; 

但結果將是

hello i _ animal _ dog and and _ tree 

如何我可以只更換第一和第二個字,而不是取代第三個單詞嗎?

+0

的可能的複製(HTTP [PHP STR \ _replace()有限制PARAM?]://計算器。 com/questions/8510223/php-str-replace-with-a-limit-param) – Rulisp

+0

@Rulisp對str_replace()沒有限制參數,有一個計數參數,但允許你傳入一個變量作爲指針爲了獲得被替換的字符串的實例數量。它實際上並不允許您限制要替換的實例的數量。 – Dave

回答

0

我認爲這是你正在尋找的結果是:

$subject = "hello i love animal love dog and and love tree"; 
$search = "love"; 
$replace = "_"; 

$pos = strrpos($subject, $search); 

$first_subject = str_replace($search, $replace, substr($subject, 0, $pos)); 
$subject = $first_subject . substr($subject, $pos, strlen($subject)); 

echo $subject; 

演示here

+1

哦最好的答案^ _ ^ –

0

這是一個免費的正則表達式路:

碼(Demo):

$test = "hello i love animal love dog and and love tree"; 
$test=substr_replace($test,"_",strpos($test,"love"),4); 
$test=substr_replace($test,"_",strpos($test,"love"),4); 
echo $test; 

輸出:

hello i _ animal _ dog and and love tree 

這種方法非常簡單,因爲它同樣的方法兩次 - 每次消除「一見鍾情」。

+0

不工作,我想輸出'你好我_動物_狗和愛樹'我怎麼辦? –

+0

@mongkontiya對不起我的錯誤,我已經解決了我的方法。我認爲這比我的第一種方法更簡單。 – mickmackusa

相關問題