Reputation: 1207
I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN"
in a sentence like "MAN live in WAN"
and 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;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
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.
Thanks in advance !
Upvotes: 2
Views: 913
Reputation: 7240
This also should work!
$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;
Upvotes: 1
Reputation: 3636
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Upvotes: 3
Reputation: 1326
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
Upvotes: 2