2012-11-27 88 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

相关问题