1

In PHP, Suppose in a string $str = "How are you";

"are" can be detected by strpos("are",$str);

How to retrieve that "w r y" is present in $str? ("WheRe are You")

I have tried the above. Using wildcard characters like * did not give me desired results..

JSON C11
  • 11,272
  • 7
  • 78
  • 65
Sharukh Mohamed
  • 55
  • 1
  • 12
  • Do you just want to know whether the characters are present or not or whether they are present in the given sequence? – RST Apr 09 '15 at 07:03
  • 1
    `if ((strpos('w', $string) !== false) && (strpos('r', $string) !== false) && (strpos('y', $string) !== false)) {....}` `strpos()` doesn't allow wildcard characters – Mark Baker Apr 09 '15 at 07:04
  • I think you should try with regular expressions – marcosh Apr 09 '15 at 07:05
  • However, [fnmatch()](http://www.php.net/manual/en/function.fnmatch.php) does accept wildcard characters: `if (fnmatch('*w*r*y*', $string)) {....}` It is case-sensitive, but `if (fnmatch('*[Ww]*[Rr]*[Yy]*', $string)) {....}` will work case-insensitive, as would `if (fnmatch('*w*r*y*', strtolower($string))) {....}` – Mark Baker Apr 09 '15 at 07:06

1 Answers1

2

Use a regular expression:

if (preg_match('/w.*r.*y/i', $str)) {
    ...
}

This requires them to be in this specific order. If you want to match them in any order, it should be:

if (preg_match('/(?=.*w)(?=.*r)(?=.*y)/', $str)) {

see match multiple words in any order with regex

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612