1

I'm trying to use strpos to search for some key words in a string using PHP. My question is how would I go about adding a array so I search for "keyword1" and "keyword2" to the code below.

if (strpos($string,'keyword1') !== false) {
$hasstring = "yes";
}

Thanks

Tabatha M
  • 171
  • 2
  • 6
  • 13
  • 1
    Could you be more specific? I have no idea what you're trying to achieve.. – Wouter Dorgelo Jul 17 '12 at 00:01
  • Are you searching for either KW1 or KW2? I don't understand why you say you want to add an array -- that confuses the question. – MJB Jul 17 '12 at 00:01
  • possible duplicate of [Using an array as needles in strpos](http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos) – Mołot Feb 24 '14 at 12:39

2 Answers2

8

You can't give strpos an array, so you will have to do it manually.

$keywords = array('keyword1', 'keyword2');

foreach($keywords as $keyword) {
    if (strpos($string, $keyword) !== false) {
        $hasString = true;
        break; // stops searching the rest of the keywords if one was found
    }
}
drew010
  • 68,777
  • 11
  • 134
  • 162
-1

If i understand your question correctly, an array is not needed. You can simply use strpos twice with an or (in php, ||) operator

if (strpos($string,'keyword1') || strpos($string,'keyword2')) {
$hasstring = "yes";
}
MrGlass
  • 9,094
  • 17
  • 64
  • 89
  • This only accounts for 2 keywords, what about "n" keywords? – antoniovassell Feb 13 '17 at 09:33
  • I think array could also be a possibility if you are searching for a list of possible keywords in a text file. E.G search for tech skills in a resume, array could content $skills =(Html, Java, PHP, mysql, Oracle, android) – Asuquo12 Oct 19 '17 at 05:24