Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'

like image 718
Ben Avatar asked Mar 07 '12 09:03

Ben


People also ask

How do you replace the first occurrence of a character in a string?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How can I replace part of a string in PHP?

The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.


3 Answers

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.

like image 164
Milind Ganjoo Avatar answered Oct 05 '22 06:10

Milind Ganjoo


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

like image 24
mishu Avatar answered Oct 03 '22 06:10

mishu


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

like image 33
Uday Sawant Avatar answered Oct 02 '22 06:10

Uday Sawant