0

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);
}
1
  • Is your current code not working? How did the results differ? Else there isn't much to optimize, except alternatively using preg_replace_callback and then invoking other stuff().
    – mario
    Jul 28, 2013 at 19:23

1 Answer 1

2
$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> 
3
  • I just edited my answer with code that I ran and the result that I got. It worked fine, so I don't know what might be causing the trouble.
    – Expedito
    Jul 28, 2013 at 20:01
  • I'd change \s? to \s+, as he wants to match at least one space.
    – Will
    Jul 28, 2013 at 20:27
  • @Will - How do you know that? His expression had exactly one space. Maybe he wants to match one space or less. However, I don't see any danger in matching with no spaces or many. Do you suppose that he has something like "Approved87.34.21" in the text that he wants to avoid removing?
    – Expedito
    Jul 28, 2013 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.