正则表达式,如何替换不包含单词的字符串?
我试图用regular expressions
替换一个字符串,并且这个字符串不包含特定的单词。正则表达式,如何替换不包含单词的字符串?
这里是字符串:
$string = 'mysql_fetch_array($stmt = mysql_query($query));' // Shouldn't match
$string = 'mysql_fetch_array($stmt));' // Should match
正则表达式:
preg_replace('/^(.*)mysql_fetch_(.*)\([ ]?.*(?!mysql_query).*[ ]?\)(.*)$/', $value, $string);
但两个串匹配上述表达式。
我该如何更换第二个字符串?
如何:
$arr = array('mysql_fetch_array($stmt = mysql_query($query));', 'mysql_fetch_array($stmt));');
$value = 'NEW($1)';
foreach($arr as $string) {
$string = preg_replace('/^.*?mysql_fetch_[^(]+\(*(\$\w+)(?!.* = mysql_query).*\);$/', $value, $string);
echo $string,"\n";
}
输出:
mysql_fetch_array($stmt = mysql_query($query));
NEW($stmt)
它正在工作,但我想用括号捕捉'$ stmt',我该怎么做? – 2014-09-23 11:50:02
@thomash:看到我的编辑,是你想要的吗? – Toto 2014-09-23 11:58:49
为什么使用正则表达式。 PHP有一个字符串替换方法:正则表达式总是你应该做的最后一个选择。
str_replace("[new sub]", "[old sub]", "[whole string]");
“正则表达式总是你应该做的最后一个选择。” **为什么?**我的意思是,它非常强大。为什么让它成为最后的选择? – 2014-09-23 12:05:00
所以含有'的mysql_query($查询)'不应该匹配的字符串? – aelor 2014-09-23 10:52:30