Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using str_replace so that it only acts on the first match?

Tags:

string

php

I want a version of str_replace() that only replaces the first occurrence of $search in the $subject. Is there an easy solution to this, or do I need a hacky solution?

like image 579
Nick Heiner Avatar asked Aug 10 '09 00:08

Nick Heiner


2 Answers

There's no version of it, but the solution isn't hacky at all.

$pos = strpos($haystack, $needle); if ($pos !== false) {     $newstring = substr_replace($haystack, $replace, $pos, strlen($needle)); } 

Pretty easy, and saves the performance penalty of regular expressions.


Bonus: If you want to replace last occurrence, just use strrpos in place of strpos.

like image 106
zombat Avatar answered Nov 17 '22 23:11

zombat


Can be done with preg_replace:

function str_replace_first($search, $replace, $subject) {     $search = '/'.preg_quote($search, '/').'/';     return preg_replace($search, $replace, $subject, 1); }  echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');  // outputs '123def abcdef abcdef' 

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).


Though, see zombat's answer for a more efficient method (roughly, 3-4x faster).

like image 36
karim79 Avatar answered Nov 17 '22 23:11

karim79