开发者

string manipulation in PHP: replace only the first occurrence of a word in a string

开发者 https://www.devze.com 2023-01-05 21:36 出处:网络
what to do if I want to replace only the first occurrence of a word in a string. eg: I want to change the first occurrence of heelo in a string with kiran.

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

input string == **"hello worl开发者_如何转开发d i am a noob hello to all"**
output string == **"kiran world i am a noob hello to all"**

the str_replace is not working.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号