paj7499 Posted October 4, 2013 Share Posted October 4, 2013 Hi I am trying to learn regular expression and am getting some unexpected results! $sentence = "This sentence contains several zzz "; if(preg_match("/z{1}/",$sentence)) { echo "Regular expression found!"; } else { echo "Regular expression NOT found!"; } The above code is echoing out “Regular expression found. I am confused. Shouldn't “/z{1}/” return true only if there is only one z in the string not zzz. What am I missing? Quote Link to comment https://forums.phpfreaks.com/topic/282696-php-preg_match/ Share on other sites More sharing options...
AbraCadaver Posted October 4, 2013 Share Posted October 4, 2013 No it is looking for a match of z repeated 1 time and it found 1 z. Roughly the same as [z] (match a z character) If you want to find a z not followed by a z then something like [z][^z]. For your pattern, if you did a preg_match_all() you'd get 3 matches for 3 single z. Quote Link to comment https://forums.phpfreaks.com/topic/282696-php-preg_match/#findComment-1452514 Share on other sites More sharing options...
.josh Posted October 4, 2013 Share Posted October 4, 2013 The exact pattern will vary depending on what you are actually trying to match. For example if you want to find a certain whole word, you could do function isWordFound($haystack,$needle) { return (bool) preg_match('~\b'.$needle.'\b~',$haystack); } $string = "foobar"; $word = "foo"; echo isWordFound($string,$word); // output: false $string = "foo bar"; $word = "foo"; echo isWordFound($string,$word); // output: true Quote Link to comment https://forums.phpfreaks.com/topic/282696-php-preg_match/#findComment-1452607 Share on other sites More sharing options...
paj7499 Posted January 24, 2014 Author Share Posted January 24, 2014 Hi I am still confused $subject = "This sentence contain several 'azzz' words";$pattern = "/az{2}/"; if (preg_match($pattern, $subject)) { echo 'Regular expression <b>found!</b>'; } else { echo 'Regular expression <b>not</b> found!'; } the above code is returning true! ('Regular expression found!) Shouldn't preg_match return false. My understanding is that pattern = "/az{2}/" means match an a followed by exactly zz (2 z's not 3). am i wrong? Quote Link to comment https://forums.phpfreaks.com/topic/282696-php-preg_match/#findComment-1466348 Share on other sites More sharing options...
Eshe Posted January 24, 2014 Share Posted January 24, 2014 Your pattern matches any string with "azz" in it, followed or preceded by anything. If you don't want it to match "azzz" you'll have to be more specific. For example: /^azz$/ would only match the string "azz", /azz(?!z)/ would match "azz" not followed by "z" anywhere in the string. Quote Link to comment https://forums.phpfreaks.com/topic/282696-php-preg_match/#findComment-1466392 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.