我试图用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)
为什么使用regex。PHP有一个字符串替换方法:Regex始终是您应该做出的最后选择。
str_replace("[new sub]", "[old sub]", "[whole string]");
http://php.net/manual/en/function.str-replace.php