Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Regular Coder
    Join Date
    Oct 2003
    Location
    Australia
    Posts
    112
    Thanks
    0
    Thanked 0 Times in 0 Posts

    regex for center

    Hi

    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

  • #2
    Regular Coder trib4lmaniac's Avatar
    Join Date
    Feb 2004
    Location
    Cornwall, UK
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    PHP Code:
    $str2 preg_replace('|<center.*?>.*?</center>|msi'''$str);
    if(
    preg_match('|<center.*?>|msi'$str2)) {
      echo 
    'unmatched center tag';

    Untested, but something like that anyway.

  • #3
    Regular Coder
    Join Date
    Oct 2003
    Location
    Australia
    Posts
    112
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thank you very much. I'll try it out.

  • #4
    Regular Coder trib4lmaniac's Avatar
    Join Date
    Feb 2004
    Location
    Cornwall, UK
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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
    PHP Code:
    $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.)

  • #5
    Regular Coder
    Join Date
    Oct 2003
    Location
    Australia
    Posts
    112
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

  • #6
    Regular Coder trib4lmaniac's Avatar
    Join Date
    Feb 2004
    Location
    Cornwall, UK
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Lol, yeah. The first one wasn't very good. My bad


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •