Php.net有这个preg_replace代码段
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
有没有办法在$ patterns上运行preg_match来执行类似这样的操作
如果在$ string中找到preg_match,那么preg_replace else echo no matched found found
感谢。
答案 0 :(得分:2)
似乎您要做的只是preg_replace
,它还会提醒您未发生的匹配?
以下内容适用于您:
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/pig/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
for($i=0;$i<count($patterns);$i++){
if(preg_match($patterns[$i], $string))
$string = preg_replace($patterns[$i], $replacements[$i], $string);
else
echo "FALSE: ", $patterns[$i], "\n";
}
echo "<br />", $string;
/**
Output:
FALSE: /pig/
The slow black fox jumped over the lazy dog.
*/
$string = preg_replace($patterns, $replacements, $string, -1, $count);
if(empty($count)){
echo "No matches found";
}
答案 1 :(得分:1)
这是你在寻找的地方吗?
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
foreach ($patterns as $pattern) {
if (preg_match("/\b$pattern\b/", $string)) {
echo preg_replace($pattern, $replacements, $string);
}
}