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.
    – Elon Than
    Jan 8, 2015 at 12:53
  • ^(?=.*MAN)(?=.*WAN).* Jan 8, 2015 at 12:53
  • "if strpos equals false response equals true"...?!
    – deceze
    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
    – Hoja
    Jan 8, 2015 at 12:57
  • 1
    @AvinashRaj. Can you detail using that reg. expression?
    – Hoja
    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;
            }   
2
  • 1
    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
    – andrew
    Jan 8, 2015 at 12:56
  • No he already sets the value to true at the start as well, so it'll always be true.
    – Erik
    Jan 8, 2015 at 12:56
2

Try this:

preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
2
  • 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
    – Hoja
    Jan 8, 2015 at 13:08
  • In my case $data is nothing but sentence or paragraph not array. Jan 8, 2015 at 13:10
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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.