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

时间:2013-05-21 04:27:54

标签: php

假设我有一个字符串

$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不受影响

这可能吗?

2 个答案:

答案 0 :(得分:5)

您可以像这样使用带有负向lookbehind的preg_replace:

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

现场演示:http://ideone.com/GeTsv3

答案 1 :(得分:0)

@anubhva回答很好也是替代尝试

$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); 
相关问题