PHP Regex:测试是否匹配,然后删除

时间:2013-07-28 19:20:40

标签: php regex

我想检查一些HTML中是否存在字符串,然后执行一些操作并将其从HTML中删除(如果存在)。该字符串的格式为“Approved NN.NN.NN”。编写此代码的最佳方法是什么?

$html = '<div>This is some text.  Approved 11.22.12</div>';
$pattern = '/Approved [0-9][0-9]\.[0-9][0-9]\.[0-9][0-9]/';
if (preg_match($pattern, $html)){
   stuff();
   $html = preg_replace($pattern, '', $html);
}

1 个答案:

答案 0 :(得分:2)

$pattern = '/Approved\s?\d{2}\.\d{2}\.\d{2}/';

我刚刚运行了以下代码:

$html = '<div>This is some text.  Approved 11.22.12</div>';
$pattern = '/Approved\s?\d{2}\.\d{2}\.\d{2}/';
if (preg_match($pattern, $html)){
    $html = preg_replace($pattern, '', $html);
}
echo $html;

输出:

<div>This is some text.  </div>