phpstringvalidationcontains

Validate that a multi-word phrase exists in a string


I have this function to check for word sequences:

function sequence($arr_scheme = [], $arr_input = [])
    {
        $sequence_need = array_values(array_intersect($arr_scheme, $arr_input));
        if(!empty($arr_input) && ($sequence_need == $arr_input)):
            return true;
        else:
            return false;
        endif;
    }

There were my sample and scheme variables:

$sample = "branch of science";
$scheme = "The branch of science concerned of nature and property of matter and energy";

I have converted to array:

$arr_sample = explode(" ",trim(rtrim(rtrim($sample,".")," ")));
 echo 'Sample:';
var_dump($arr_sample);

enter image description here

$arr_scheme = explode(" ",trim(rtrim(rtrim($scheme,".")," ")));
echo '<br/>Scheme:';
var_dump($arr_scheme);

enter image description here

Now, I check the sequences:

$result = sequence($arr_scheme, $arr_sample);

The result:

echo '<br/>Result:';
var_dump($result);

enter image description here

When I set the variable $sample to "branch science" the result will return true. This was fine.

However when I set the variable sample to "branch of science" the result will return false .

Reason - the word of was more than 1, how I can solve this problem?

word of **<code>of</code>** was more than 1 make this return to false


Solution

  • Find first input word in the scheme (can be multiple).
    Then run recursive for rests of arrays.

    function sequence($arr_scheme = [], $arr_input = [])
    {
      if (!$arr_input) return true;
      $first = array_shift($arr_input);
      $occurences = array_keys($arr_scheme, $first);
      if (!$occurences) return false;
    
      foreach ($occurences as $o) { // loop first word occurences
        $found = sequence(array_slice($arr_scheme, $o), $arr_input);
        if ($found) return true;
      }
      return false;
    }
    

    First word later occurences should not matter anything for match.
    So, this tail-recursion function will work even better:

    function sequence($arr_scheme = [], $arr_input = [])
    {
      if (!$arr_input) return true;
      $first = array_shift($arr_input);
      $index = array_search($arr_scheme, $first);
      if ($index === false) return false; // not found
      return sequence(array_slice($arr_scheme, $index), $arr_input);
    }