我想检查一个字符串是否包含两个特定的单词。
例如:
我需要在"MAN" & "WAN"
和"MAN live in WAN"
这样的句子中检查字符串是否包含returns true else false
。
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
这是正确的方法还是我要改变它?如何实现这一点任何建议或想法将受到高度赞赏。
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
提前致谢!
答案 0 :(得分:3)
差不多好。如果不包含单词,则需要将响应设置为false。现在它总是给出真实的。
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
答案 1 :(得分:2)
试试这个:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
答案 2 :(得分:1)
这也应该有用!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;