php replace first occurrence of string from 0th po

2019-02-04 06:36发布

问题:

This question already has an answer here:

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

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:

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.



回答2:

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



回答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



回答4:

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


回答5:

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


回答6:

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


回答7:

This function str_replace is the one you are looking for.



回答8:

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>';