php replace first occurrence of string from 0th position [duplicate] php replace first occurrence of string from 0th position [duplicate] php php

php replace first occurrence of string from 0th position [duplicate]


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.


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


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