2012-11-27 86 views
1

所以我有以下字符串。試圖只替換Php中的字符串的第一個實例,而不是所有的替換

 John Hotmail([email protected]) , John Hotmail([email protected]) , 

我想只替換上面的John Hotmail的第一個實例,但是不管我嘗試它如何替換它們。我已經通過論壇尋找答案,我已經嘗試了所有的解決方案。我已經嘗試了以下。

$string= "/John Hotmail([email protected]) ,/"; 
    //$string= "John Hotmail([email protected]) ,"; 
    $count = 1; 
    $descriptionMessage = $name . ' said hello' . $model->Name . ' to the following people:' . $listParticipants; 
    $descriptionMessage = preg_replace($string, "", $descriptionMessage,$count); 

我試過類似的東西與str_replace。我已將字符串消息更改爲包含/以及在其中沒有/。我已經把計數設置爲0,在這種情況下,它不會去除任何東西,我已經把它設置爲1,如上所示,它刪除了兩個John Hotmail字符串。我所輸入的設置中沒有一個剛剛刪除了第一個輸入,但我不知道爲什麼。我目前在Yii框架的控制器類中使用此代碼(如果有幫助的話)。謝謝你的幫助。

+0

它不太明白你正在嘗試實現什麼,你可以嘗試換一種方式表述您的問題,所以很容易回答。它看起來像我需要更多的信息和$ name和$ listParticipants中包含的內容 - 如果你描述你正在嘗試做什麼,那麼可能有另一種可能的解決方案。 –

+0

嗨,對於缺乏清晰度的抱歉,$ listParticipants只是包含John Hotmail([email protected]),John Hotmail([email protected])的字符串。 $ name只是放入字符串的名稱,名稱將與$ listParticipants不同。 – Chaney

回答

2

這將替換第一次出現:

$string = 'John Hotmail([email protected]) ,'; 
$descriptionMessage = 'John Hotmail([email protected]) , John Hotmail([email protected]) ,'; 

$position = strpos($descriptionMessage, $string); 
if ($position !== false) { 
    $descriptionMessage = substr_replace($descriptionMessage, '', $position , strlen($string)); 
} 
+0

非常好,這工作的魅力。非常感謝你,先生!在旁邊注意,你有什麼想法爲什麼str_replace和preg_replace不工作? – Chaney

+1

沒問題,不知道爲什麼preg_replace不起作用,但答案中的代碼總是比正則表達式快。 – MrCode

+0

很酷,再次感謝! – Chaney

相關問題