4

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?

2
  • you've included a limit on the replacements of 1 - do you really just want to replace the first instance of the pattern match? Anyway, I think including this when there is no match may be causing your problem with some replacement patterns. Commented Aug 2, 2010 at 23:20
  • See [ PHP: str_replace that only acts on the first match? ](stackoverflow.com/questions/1252693/…). Commented Aug 2, 2010 at 23:21

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use T-Regx library:

pattern('[a-z]+')->replace($string)->first()->with($replace);

and also you should not use preg_quote(), as it's not safe - try Prepared Patterns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.