Regular Expressions Help

Discussion in 'PHP' started by PHPGator, Apr 4, 2008.

  1. #1
    Okay, it is official, the regular expression stuff is already giving me a headache. Can someone please explain why this is not working?

    It seems pretty simple and logical to me, but it is resulting in "Not match". Why?

    <?php
    /*
    	'/^\<test\<[a-zA-Z0-9]\<\/test\>$/'
    	<test>hello</test>
    */
    
    $pattern = '/^\<test\<[a-zA-Z0-9]\<\/test\>$/';
    $string   = "<test>hi</test>";
    
    if (preg_match($pattern,$string)) {
    		echo "Match";
    	} else { 
    		echo "Not match";
    }
    ?>
    PHP:
     
    PHPGator, Apr 4, 2008 IP
  2. french-webbie

    french-webbie Peon

    Messages:
    194
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,
    - no need to escape < nor >
    - you wer testing for only one character [a-zA-Z0-9]
    - the + signe means "at least one character"
    - the ? sign limits the greediness of the regexp (it stops as soon as it finds the first </test>

    /^<test>[a-zA-Z0-9]+?<\/test>$/

    one last tip: use preg_match_all with the array $matches and do a print_r of it, and start always with a little part of it at a time to be able to test each step (<test>, then <test></test>...)
    regexp are very powerful but always a pain to do it right at the first attempt ;)
     
    french-webbie, Apr 4, 2008 IP