问题
I have a string like this:
$str = "it is a test";
I want to check it for these words: it
, test
. I want to it returns true
if there is at least one of those words in the string.
Here is what I did: (though it does not work)
$keywords = array ('it', 'test');
if(strpos($str, $keywords) !== false){ echo 'true';}
else echo 'false';
How can I do that?
回答1:
simply checking using preg_match
, you can add many different words in the pattern, just use a separator |
in between words
$str = "it is a test";
if (preg_match("[it|test]", $str) === 1)
{
echo "it matches";
}
Sorry I didnt know you were dealing with other languages, you can try this
$str = "你好 abc efg";
if (preg_match("/\b(你好|test)\b/u", $str) === 1)
{
echo "it matches";
}
I also need to mention that \b
means word boundary, so it will only matches the exact words
回答2:
The easiest way would be to user the explode function, this looks like:
$str = "it is a test"; // Remember your quotes!
$keywords = array ('it', 'test');
$str_array = explode(" ", $str);
$foundWords = [];
foreach ($keywords as $key)
{
if (in_array($key, $str_array))
{
$foundWords[] = $key;
}
}
foreach($foundWords as $word)
{
print("Word '{$word}' was found in the string '{$str}'<br />");
}
This is a function with printing also
This gave me the result:
Word 'it' was found in the string 'it is a test'
Word 'test' was found in the string 'it is a test'
I think the issue with your code is that it is trying to match an array as a whole to the string, try doing it inside a foreach
loop.
Another way would be something such as:
$keywords = array ('it', 'test');
echo (strpos($srt, $keywords[0]) ? "true" : "false");
echo (strpos($srt, $keywords[1]) ? "true" : "false");
回答3:
I am not sure, so sorry of i am wrong. I think strpos doesnt work with arrays?
Try to do:
$array = ('it', 'test');
for($i=0;$i<$array.length;$i++){
//here the strpos Method but with $array[$i]
}
来源:https://stackoverflow.com/questions/33653956/how-to-check-multiple-words-exist-in-the-string-returns-true-it-there-is-at-le