检查给定的两个单词是否存在于 PHP 字符串中
Check whether the given two words are existing in a PHP string
我想检查一个字符串是否包含两个特定的单词。
例如:
我需要在 "MAN live in WAN"
和 returns true else false
.
这样的句子中检查字符串是否包含 "MAN" & "WAN"
我试过的是以条件方式循环字符串函数:-
<?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.
提前致谢!
试试这个:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
差不多好了。如果不包含单词,您需要将响应设置为 false。现在它总是给出 true。
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
这也应该有效!
$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;
我想检查一个字符串是否包含两个特定的单词。
例如:
我需要在 "MAN live in WAN"
和 returns true else false
.
"MAN" & "WAN"
我试过的是以条件方式循环字符串函数:-
<?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.
提前致谢!
试试这个:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
差不多好了。如果不包含单词,您需要将响应设置为 false。现在它总是给出 true。
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
这也应该有效!
$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;