29

I want to search and replace the first word with another in php like as follows:

$str="nothing inside";

Replace 'nothing' to 'something' by search and replace without using substr

output should be: 'something inside'

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Ben
  • 4,392
  • 3
  • 23
  • 20
  • Regular expressions are much more expensive performance wise than working with other methods. **Never default to regex unless you have given serious consideration to other programming approaches to your problem!** With currently 36K views already how much human time has been wasted around the world via by bad performance programed by amateurs who did *not* have a better / correct approach to their related problems? – John Jun 26 '18 at 12:28

8 Answers8

64

Use preg_replace() with a limit of 1:

preg_replace('/nothing/', 'something', $str, 1);

Replace the regular expression /nothing/ with whatever string you want to search for. Since regular expressions are always evaluated left-to-right, this will always match the first instance.

Milind Ganjoo
  • 1,260
  • 11
  • 13
  • 3
    This solution has escaping issues if you're just using generic strings, such as if $ and such are within the string. http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match has a more generic solution. – Anther Oct 17 '12 at 18:55
  • 1
    **Regular expressions should *never* be treated as the first go-to option in any programming language** due to their higher resource usage *period*. For the less experienced: if you have not spent serious time trying to determine another approach to the problem then it's far from the appropriate time to even consider regex. – John Jun 26 '18 at 12:23
14

on the man page for str_replace (http://php.net/manual/en/function.str-replace.php) you can find this function

function str_replace_once($str_pattern, $str_replacement, $string){

    if (strpos($string, $str_pattern) !== false){
        $occurrence = strpos($string, $str_pattern);
        return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
    }

    return $string;
}

usage sample: http://codepad.org/JqUspMPx

mishu
  • 5,347
  • 1
  • 21
  • 39
  • 1
    same as preg_replace('/search/','replace',$str,1); – Ben Mar 07 '12 at 10:05
  • 2
    @Ben The functions are the similar, but definitely not the same. If you use a character that needs to be escaped by a regular expression, you will get unexpected errors if you use preg_replace. – Anther Oct 17 '12 at 19:54
3

try this

preg_replace('/^[a-zA-Z]\s/', 'ReplacementWord ', $string)

what it does is select anything from start till first white space and replace it with replcementWord . notice a space after replcementWord. this is because we added \s in search string

Uday Sawant
  • 5,748
  • 3
  • 32
  • 45
0
preg_replace('/nothing/', 'something', $str, 1);
trex005
  • 5,015
  • 4
  • 28
  • 41
  • This will replace all occurrence. preg_replace('/OR/',' ',$str,1) replaces first occurrence of 'OR' but not only the leading occurrence – Ben Mar 07 '12 at 09:42
  • 1
    Code-only answers are low value on Stackoverflow. Please explain how your answer works and why it is a good idea. Those who are not familiar with `preg_replace()` may not know why you chose this function nor what the parameters are doing. Please do some something/anything to improve the educational value of this post. – mickmackusa Jul 17 '18 at 06:06
-1

I ran to this issue and wanted a solution and this wasn't 100% right for me because if the string was like $str = "mine'this , the appostrophe would cause a problem. so I came up with a litle trick :

$stick='';
$cook = explode($str,$cookie,2);
        foreach($cook as $c){
            if(preg_match("/^'/", $c)||preg_match('/^"/', $c)){
                //we have 's dsf fds... so we need to find the first |sess| because it is the delimiter'
                $stick = '|sess|'.explode('|sess|',$c,2)[1];
            }else{
                $stick = $c;
            }
            $cookies.=$stick;
        }
Jayo2k
  • 251
  • 3
  • 14
-1

This checks and caches the first substring position in one command, next replacing it if present, should be the more compact and performant:

if(($offset=strpos($string,$replaced))!==false){
   $string=substr_replace($replaced,$replacer,$offset,strlen($replaced));
}
Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • yes but these are an if and 2 function calls, nested, it should be auto explicative if you can understand the question, otherway you are not interested in the answer. AND I used very auto-explicative name variables, usually this should be enough to explain when the purpose of the code is known and the code lines are few – Luca C. Jul 18 '18 at 16:30
-3

This function str_replace is the one you are looking for.

steveoh
  • 306
  • 2
  • 10
  • 7
    that 4th parameter counts the replaces performed, doesn't limit the replacements to a number – mishu Mar 07 '12 at 09:25
  • You are right. Will edit my answer. – steveoh Mar 07 '12 at 09:27
  • @steveoh: str_replace replaces all occurrence, but i want only the first occurrence if it exists in the start like ltrim function remove the first space only. – Ben Mar 07 '12 at 09:30
  • Obviously you should stick to the answer of *mganjoo*, would accept it as the answer. – steveoh Mar 07 '12 at 09:32
-4

ltrim() will remove the unwanted text at the beginning of a string.

$do = 'nothing'; // what you want
$dont = 'something'; // what you dont want
$str = 'something inside';
$newstr = $do.ltrim( $str , $dont);
echo $newstr.'<br>';
  • ltrim() removes all characters in the given list, not the sequence of characters. Please update your answer. – Calin Aug 22 '13 at 09:35