我需要一个replace string-once函数,相信preg-u匹配可能是我最好的选择。
我在使用这个,但是由于使用的动态性,有时这个函数的行为很奇怪:
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));
}
现在我采用这种方法,但已经遇到下面列出的错误…我正在用这个函数分析各种HTML字符串,因此很难给出导致错误的值。到目前为止,我使用下面的80%显示了这个错误。
function str_replace_once($remove , $replace , $string)
{
$remove = str_replace('/','\/',$remove);
$return = preg_replace("/$remove/", $replace, $string, 1);
return $return;
}
错误:
警告:preg_replace()[函数.preg replace]:编译失败:偏移量0处没有重复的内容
有人能改进解决方案吗?