php replace first occurrence of string from 0th position

61,035

Solution 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.

Solution 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

Solution 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

Share:
61,035
Ben
Author by

Ben

Simplicity is prerequisite for reliability.

Updated on July 22, 2020

Comments

  • Ben
    Ben almost 4 years

    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'