key2starz
key2starz

Reputation: 757

PHP Regex: Test if matches, and then remove

I want to check if a string is present in some HTML, then do some things and remove it from the HTML if it is present. The string has the format of "Approved NN.NN.NN". What is the best way to write this code?

$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);
}

Upvotes: 0

Views: 61

Answers (1)

Expedito
Expedito

Reputation: 7795

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

I just ran the following code:

$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;

Output:

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

Upvotes: 2

Related Questions