PHP. Check if all array elements are in string.
I have an array, $my_array
containing the element n
and the line $my_string
. I want to check if ALL items $my_array
are in $my_string
. The order in which they appear on the line is not important as long as they are all there. I am looking for the most efficient solution to get it TRUE
only if all elements are present.
TRUE:
$my_array = array("big", "blue", "sky", "dog");
$my_string = "my big dog loves the blue sky";
FALSE:
$my_array = array("big", "blue", "sky", "dog");
$my_string = "the big blue sky";
source to share
Here you go, don't be afraid of arrays.
$my_array = array("big", "blue", "sky", "dog");
$my_string = "my big dog loves the blue sky"
function arrayInString( array $my_array, $my_string ){
$my_string = explode(' ', $my_string);
// difference return all elements of array one not in array two
$diff = array_diff($my_array, $my_string);
if(empty( $diff )){
//if there is no difference there are no elements not in the string.
return true;
}
return false;
}
Fun without loops!
If there is punctuation, you can use
preg_split('/^\w/', $my_string );
instead explode
source to share
2 ways I can think of. This first path is great if you know for sure that you can always share the given character (s). It's short, sweet and simple. Using array_dif
and simpleexplode
function isArrayInString($str, $ara, $splitter=" ") {
$ret = array_diff($ara, explode($splitter, $str));
return empty($ret);
}
However , this does not seem very dynamic and limits you to the base of the string "splitting". A simpler, possibly better way would be to loop through your array and ensure that each array value exists in a string using strpos
.
function isArrayInString($str, $ara, $splitter=" ") {
foreach($ara as $v) if (strpos($str , $v) === false) return FALSE;
return $TRUE;
}
So something like:
$myArray = array("big", "blue", "sky", "dog");
$myString = "my big dog loves the blue sky";
echo isArrayInString($myString, $myArray);
Will output TRUE
So far, something like:
$myArray = array("big", "blue", "sky", "dog");
$myString = "the big blue sky";
echo isArrayInString($myString, $myArray);
Will output FALSE
source to share
This should work for you:
<?php
$my_array = array("big", "blue", "sky", "dog");
$my_string = "my big dog loves the blue sky";
$result = 0;
foreach($my_array as $value) {
if (strpos($my_string, $value) !== false)
$result+=1;
}
if($result == count($my_array))
echo "true";
else
echo "false";
?>
Output:
true
source to share