仅用php preg_replace替换字符串一次 [英] Replace string only once with php preg_replace

查看:341
本文介绍了仅用php preg_replace替换字符串一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need a replace string once function and believe preg_match might be my best bet.

我正在使用此功能,但是由于使用的动态性,有时此功能的行为会很奇怪:

I was using this, but due to the dynamicness of use, sometimes this function behaves strangely:

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%显示此错误.

Now I am taking this approach but have ran to to the error listed below.... I'm parsing all kinds of html strings with this function, so its hard to give a value thats causing the error. As of now 80% of my uses of the below show this error .

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

错误:

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

Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 0

任何人都可以完善解决方案吗?

Can anyone refine a solution?

推荐答案

您正在寻找preg_quote,而不是试图自己逃避\(不需要[+等许多其他内容)考虑在内)

You are looking for preg_quote instead of trying to escape the \ yourself (which doesn't take [, + and many others into account):

$return = preg_replace('/'.preg_quote($remove,'/').'/', $replace, $string, 1);

这篇关于仅用php preg_replace替换字符串一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆