我需要一个替换字符串一次函数,并且相信 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));
}
现在我正在采用这种方法,但遇到了下面列出的错误......我正在用这个函数解析各种 html 字符串,所以很难给出导致错误的值。截至目前,我对以下内容的 80% 使用都显示了此错误。
function str_replace_once($remove , $replace , $string)
{
$remove = str_replace('/','\/',$remove);
$return = preg_replace("/$remove/", $replace, $string, 1);
return $return;
}
错误:
任何人都可以改进解决方案吗?
最佳答案
您正在寻找 preg_quote
而不是试图自己逃避 \
(这不考虑 [
、 +
和许多其他因素):
$return = preg_replace('/'.preg_quote($remove,'/').'/', $replace, $string, 1);
关于regex - 只用 php preg_replace 替换字符串一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3392508/