用php preg_replace只替换字符串一次

atw*_*pub 3 php regex string

我需要一个替换字符串一次功能,并相信preg_match可能是我最好的选择.

我正在使用它,但由于使用的动态性,有时这个函数表现得很奇怪:

function str_replace_once($remove , $replace , $string)
{
    $pos = strpos($string, $remove);
    if ($pos === false) 
    {
    // Nothing found
    return $string;
    }
    return substr_replace($string, $replace, $pos, strlen($remove));
} 
Run Code Online (Sandbox Code Playgroud)

现在我采用这种方法,但已经遇到下面列出的错误....我正在使用此函数解析所有类型的html字符串,因此很难给出导致错误的值.截至目前,我对以下80%的使用显示此错误.

function str_replace_once($remove , $replace , $string)
{
    $remove = str_replace('/','\/',$remove);
    $return = preg_replace("/$remove/", $replace, $string, 1);  
    return $return;
}  
Run Code Online (Sandbox Code Playgroud)

错误:

警告:preg_replace()[function.preg-replace]:编译失败:在偏移量0处不重复

有人可以改进解决方案吗?

Wri*_*ken 6

你正在寻找preg_quote而不是试图逃避\自己(不考虑[,+并考虑许多其他人):

$return = preg_replace('/'.preg_quote($remove,'/').'/', $replace, $string, 1);
Run Code Online (Sandbox Code Playgroud)