Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

regex - Replace string only once with php preg_replace

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

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

error:

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

Can anyone refine a solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...