View Full Version : regex for center

10-15-2004, 03:46 AM

I'm trying to come with a quick function to check a string for matching <center> & </center> tags. If a <center> tag is open and a matching ending tag not found, an error is throw. I know this has to be done using regex but I'm regex-challenged. Can someone point something for me to explore? Thanks

10-15-2004, 03:19 PM
$str2 = preg_replace('|<center.*?>.*?</center>|msi', '', $str);
if(preg_match('|<center.*?>|msi', $str2)) {
echo 'unmatched center tag';

Untested, but something like that anyway.

10-18-2004, 05:34 AM
thank you very much. I'll try it out.

10-18-2004, 09:04 PM
Looking back at it, it probably wouldn't work as intended. It would be better just to count the occurences of <center> and </center> to see if they match

$open_tags = preg_match_all('/<center.*?>/msi', $str, $matches);
$close_tags = substr_count($str, '</center>');
if($open_tags != $close_tags) {
echo 'Unmatched center tag[s].';
Again untested, but should work.

(Better than the last because it matches extra <center> and </center> tags no matter how they are nested.)

10-21-2004, 05:22 AM
Thanks. I tried the other one, it didn't work. What it did was that the string return was empty when it passed the condition but an error message was returned when the string failed the condition. Also, someone could enter </center> and pass the condition. hehe

The second code works beautifully. Thank you so much. :) I learn something new today. :D

10-21-2004, 01:31 PM
Lol, yeah. The first one wasn't very good. My bad :(