尝试仅替换Php中字符串的第一个实例,而是替换所有字符串

时间:2012-11-27 12:42:24

标签: php yii

所以我有以下字符串。

      John Hotmail(johnhotmail@hotmail.com) , John Hotmail(johnhotmail@hotmail.com) ,

我正在尝试仅更换上述John Hotmail的第一个实例,但无论我尝试什么,它都会替换它们。我已经通过论坛寻找答案,我已经尝试了所有的解决方案。我尝试了以下内容。

    $string= "/John Hotmail(johnhotmail@hotmail.com) ,/";
   //$string= "John Hotmail(johnhotmail@hotmail.com) ,";
    $count = 1;
    $descriptionMessage = $name . ' said hello' . $model->Name . ' to the following people:' . $listParticipants;
    $descriptionMessage = preg_replace($string, "", $descriptionMessage,$count);

我用str_replace尝试过类似的东西。我已将字符串消息更改为包含/以及没有/在其中。我已将count设置为0,在这种情况下,它不会删除任何内容,我已将其置于1,如上所述删除了两个John Hotmail字符串。我输入的所有设置都没有删除第一次出现,但我不知道为什么。我目前在Yii框架的控制器类中使用此代码,如果这有帮助。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

这将取代第一次出现:

$string = 'John Hotmail(johnhotmail@hotmail.com) ,';
$descriptionMessage = 'John Hotmail(johnhotmail@hotmail.com) , John Hotmail(johnhotmail@hotmail.com) ,';

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