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'

1
  • 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? Commented Jun 26, 2018 at 12:28

8 Answers 8

65

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution has escaping issues if you're just using generic strings, such as if $ and such are within the string. stackoverflow.com/questions/1252693/… has a more generic solution.
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.
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

2 Comments

same as preg_replace('/search/','replace',$str,1);
@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.
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

3 Comments

Me too, not so good at regEx. You can try this link [So You Want to Learn Regular Expressions?] (stedee.id.au/Learn_Regular_Expressions)
Sorry, but i cant format it properly
This answer is simply incorrect -- I don't understand why it has received 3 upvotes. It is clearly an untested post.
0
preg_replace('/nothing/', 'something', $str, 1);

2 Comments

This will replace all occurrence. preg_replace('/OR/',' ',$str,1) replaces first occurrence of 'OR' but not only the leading occurrence
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.
-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;
        }

Comments

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

1 Comment

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
-3

This function str_replace is the one you are looking for.

4 Comments

that 4th parameter counts the replaces performed, doesn't limit the replacements to a number
You are right. Will edit my answer.
@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.
Obviously you should stick to the answer of mganjoo, would accept it as the answer.
-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>';

1 Comment

ltrim() removes all characters in the given list, not the sequence of characters. Please update your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.