2

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 !

9
  • $this->checkInSentence with simple function? I'm pretty sure that you should read some more about PHP. Also your code contains logical error. Commented Jan 8, 2015 at 12:53
  • ^(?=.*MAN)(?=.*WAN).* Commented Jan 8, 2015 at 12:53
  • "if strpos equals false response equals true"...?! Commented Jan 8, 2015 at 12:54
  • 1
    @ElonThan. Can you suggest alternate methods in preg match. I'm little week in reg. expression and preg match. Also I've edited the logical part.thanks deceze Commented Jan 8, 2015 at 12:57
  • 1
    @AvinashRaj. Can you detail using that reg. expression? Commented Jan 8, 2015 at 13:00

3 Answers 3

3

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;
            }   
Sign up to request clarification or add additional context in comments.

2 Comments

it won't always return true, it'll return true of the last array item was in the string. But your answer will still work
No he already sets the value to true at the start as well, so it'll always be true.
2

Try this:

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

2 Comments

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.will it work
In my case $data is nothing but sentence or paragraph not array.
1

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.