0

while attempting a question in SO,i tried to write the regular expression which matches three characters that should be in the string.

i am following the answer Regular Expressions: Is there an AND operator?

<?php

$words = "systematic,gear,synthesis,mysterious";
$words=explode(",",$words);

$your_array = preg_grep("/^(^s|^m|^e)/", $words);

print_r($your_array);

?>

the output should be systematic and mysterious.but i am getting synthesis also.

Why is it so?what i am doing wrong?

** i dont want a new solution :) SEE HERE

Community
  • 1
  • 1
R R
  • 2,999
  • 2
  • 24
  • 42

1 Answers1

4

You can do this:

$wordlist = 'systematic,gear,synthesis,mysterious';
$words = explode(',', $wordlist);

foreach($words as $word) {
    if (preg_match('~(?=[^s]*s)(?=[^m]*m)(?=[^e]*e)~', $word))
        echo '<br/>' . $word;
}
//or
$res = preg_grep('~(?=[^s]*s)(?=[^m]*m)(?=[^e]*e)~', $words);
print_r($res);

To test the presence of a character in the string, I use (?=[^s]*s).
[^s]*s means all that is not a "s" zero or more times, and a "s".
(?=..) is a lookahead assertion and means "followed by". It is only a check, a lookahead give no characters in a match result, but the main interest with this feature is that you can check the same substring several times.

What is wrong with your pattern?

/^(^s|^m|^e)/ will give you only words that begins with "s" or "m" or "e" because ^ is an anchor and means : "start of the string". In other words, your pattern is the same as /^([sme])/.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125