views:

42

answers:

2

what to do if i want to replace only the first occurance of a word in a string. eg: I want to change the first occurance of heelo in a string with kiran.

input string == **"hello world i am a noob hello to all"**
output string == **"kiran world i am a noob hello to all"**

the str_replace is not working....

Thx in advance....

+3  A: 

You could use preg_replace. The 4th arugment of this functions allows you to set how many times a replacement should occur.

$output = preg_replace( "/$find/", $replace, $input, 1 );

If you don't want regular expression meta-characters to be interpretted in the search string, use:

$output = preg_replace( "/\\Q$find\\E/", $replace, $input, 1 );
tomit
What if both hello and kiran are stored in strings.say $find='hello';$replace='kiran';$input='hello world i am a noob hello to all';
Kiran George
I used the preg_replace('/' + $find + '/', $replace, $input, 1); But it is showing the error "Delimiter must not be alphanumeric or backslash in C:\wamp\www\test\e.php" on that line
Kiran George
I've updated my answer to account for the case you mentioned.
tomit
thank u tomit.. this is exactly what i was looking for...
Kiran George
A: 

You can use stripos() and substr_replace():

$str = "hello world i am a noob hello to all";
$needle = 'hello';
echo substr_replace($str, 'kiran', stripos($needle, $str), strlen($needle));

gives

kiran world i am a noob hello to all

stripos() gives the index of the first occurrence of a substring (case insensitive) and substr_replace() replace the substring at index i and length n by the given argument.

Felix Kling