Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试在Php中只替换字符串的第一个实例,而替换所有实例_Php_Yii - Fatal编程技术网

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

尝试在Php中只替换字符串的第一个实例,而替换所有实例,php,yii,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) , 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框架的控制器类中使用这段代码。感谢您的帮助。

这将取代第一次出现的:

$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));
}

它不太明白你想达到什么目的,你能试着重新表述你的问题以便更容易回答吗。看起来我需要更多信息以及$name和$listParticipants中包含的内容-如果您描述您正在尝试执行的操作,那么可能会有另一种可能的解决方案。您好,很抱歉不够清晰,$listParticipants只是包含John Hotmail的字符串(johnhotmail@hotmail.com),johnhotmail(johnhotmail@hotmail.com) ,. $name只是一个要放入字符串中的名称,名称将与$listParticipants不同。太好了,这很有魅力。非常感谢好先生!另外,你知道str_replace和preg_replace为什么不起作用吗?没问题,不知道preg_replace为什么不起作用,但答案中的代码无论如何都会比regex快。