str_replace_first: Only replace first occurence

Wed, 18/08/2010
If you want to replace text in PHP5, you use str_replace. With this function every occurence of what you search is replaced. If you only want to replace once (the first), use this function. {syntaxhighlighter brush: php;light: true; fontsize: 100; first-line: 1; }$search = 'replacethis';$replace = 'withthis'; $subject = 'inthis (replacethis replacethis)'; preg_replace('/'.$search.'/', $replace, $subject, $output), 1);{/syntaxhighlighter} You can also use this function, then you don't have to change the signature of your function: {syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; }$search = 'replacethis'; $replace = 'withthis'; $subject = 'inthis (replacethis replacethis)'; function str_replace_first ($search, $replace, $subject){ preg_replace('/'.$search.'/', $replace, $subject, $output), 1); }{/syntaxhighlighter}