替换字符串,但不替换包含该字符串的特定单词


replace string but not a specific word that contains that string

假设我有一个字符串

$string = 'this is my gal_s, not my 1_s not 2_s not 3_s';
$find = '_s';
$replace = '';

我想返回

"this is my gal_s, not my 1 not 2 not 3"

所以单词gal_s不受影响

这可能吗?

你可以像这样使用preg_replace:

$repl = preg_replace('/(?<!'bgal)_s/', '', $str);

实时演示:http://ideone.com/GeTsv3

@anubhva answer is good also alternate try

$string = 'this is my gal_s, not my 1_s not 2_s not 3_s';
$find = '_s';
$replace = '';
$arr = explode(',', $string);
$arr[1] = str_replace('_s', '', $arr[1]);
echo $string = implode($arr);