Search code examples
phppreg-replaceexplode

PHP - how to check matched words from a string?


How to match? Expected valid input:

email-sms-call or sms,email,call or sms email call or smsemailcall

Which only match when there is space in-between

<?php
function contains($needles, $haystack) {
  return count(
          array_intersect(
                  $needles, 
                  explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))
            )
          );
}

$database_column_value = 'email,sms,call';
$find_array = array('sms', 'email');
$found_array_times = contains($find_array, $database_column_value);

if($found_array_times) {
  echo "Found times: {$found_array_times}";
}
else {
  echo "not found";
}


?>

Solution

  • With preg_split function:

    function contains($needles, $haystack) {
      if (!$needles || !$haystack) 
          return false;
    
      $result = array_intersect($needles, preg_split("/[^A-Za-z0-9' -]+/", $haystack));  
      return count($result);
    }
    
    $database_column_value = 'email,sms,call';
    $find_array = ['sms', 'email', 'phone'];
    $found_array_times = contains($find_array, $database_column_value);
    
    if ($found_array_times) {
        echo "Found times: {$found_array_times}";
    } else {
        echo "not found";
    }
    

    The output:

    Found times: 2