0

Can you please tell me how can I use strops to see if a string doesn't contains any of the two specific words? (? and if)

$phrase = “how to use strops?”
if(strpos($phrase, "?|if") === false) //Is there a way I can detect the presence of
{               //either words in a sentence using one line of code that has strpos

     echo “neither word is found”;
}
bizzehdee
  • 20,289
  • 11
  • 46
  • 76
Justin k
  • 1,104
  • 5
  • 22
  • 33
  • 1
    `strpos` tells you the 1st occurrence of a string in another string. It may not be the best choice to use here. If you want to use it, you'll need to use it twice; once for `?` and once for `if`. – gen_Eric Jul 02 '13 at 14:24
  • 1
    Can't you just use `preg_match` for this? `preg_match('/\?|if/', $phrase);` – sbeliv01 Jul 02 '13 at 14:26
  • "using one line of code that has strpos" sounds a little like homework. You should also note that "strpos" does not detect "words", it detects occurences. "if" would match "lift", "swift", "if", etc. But to answer your question: `if((strpos($phrase,"?") || strpos($phrase,"if")) === false)` is one line. – Jacob S Jul 02 '13 at 14:28
  • Thanks for all of your answers and comments. `if((strpos($phrase,"?") || strpos($phrase,"if")) === false)` would be the best way for me. thanks Jacob s – Justin k Jul 02 '13 at 14:44
  • 1
    `“` and `”` are not valid string delimiters anyways. don't use a wordprocessor to edit code. – Marc B Jul 02 '13 at 14:53
  • possible duplicate of [Using an array as needles in strpos](http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos) – carla Jun 19 '15 at 14:47

2 Answers2

2

strpos() does not support regular expression. So you either use regexps (like preg_match() or do something less sophisticated like:

$phrase = "how to use strpos";
$words = array('foo', 'bar');

$matches = 0;
foreach( $words as $word ) {
   $matches += ( strpos( $phrase, $word ) !== false ) ? 1 : 0;
}

printf("%d words matches", $matches);
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
-2
if ((strpos($phrase, "?")===FALSE)$$(strpos($phrase,"if")===FALSE)) echo "neither word is found";
Godea Andrei
  • 55
  • 1
  • 9