Hoja
Hoja

Reputation: 1207

Check whether the given two words are existing in a PHP string

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.

What I've tried is looping string function in a conditional way:-

<?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

Answers (3)

deviloper
deviloper

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

Erik
Erik

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

Needhi Agrawal
Needhi Agrawal

Reputation: 1326

Try this:

preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);

Upvotes: 2

Related Questions