0

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 否则回显未找到匹配项

谢谢。

4

2 回答 2

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";
}
于 2013-09-24T08:42:07.743 回答
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);
      }
}
于 2013-09-24T08:24:48.713 回答