I'm looking for an alternative function that works the same as in_array but which could also check if the search term only contains a part of the given element instead of the whole element:
Currently working with the following script:
$attributes = array('dogs', 'cats', 'fish');
if (in_array($attributes, array('dog','cats','fishess'), true )) {
* does something for cats, but not for dogs and fish
because the function only checks if the given term is identical to the word in the array instead of only a part of the word *
}
How would I build my up function so that it passes words which only contain parts of word in the array aswell?
Preferred example would look something like this:
$words = array('fish', 'sharks');
if (*word or sentence part is* in_array($words, array('fishing', 'sharkskin')){
return 'your result matched 2 elements in the array $words
}
The solution using array_filter
and preg_grep
functions:
$words = ['fish', 'sharks', 'cats', 'dogs'];
$others = ['fishing', 'sharkskin'];
$matched_words = array_filter($words, function($w) use($others){
return preg_grep("/" . $w . "/", $others);
});
print_r($matched_words);
The output:
Array
(
[0] => fish
[1] => sharks
)
Try the code below:
<?php
$what = ['fish', 'sharks'];
$where = ['fishing', 'sharkskin'];
foreach($what as $one)
foreach($where as $other)
echo (strpos($other, $one)!==false ? "YEP! ".$one." is in ".$other."<br>" : $one." isn't in ".$other."<br>");
?>
Hope it helps =}
you can use:
array_filter($arr, function($v, $k) {
// do whatever condition you want
return in_array($v, $somearray);
}, ARRAY_FILTER_USE_BOTH);
this function call on every item in the array $arr
a function that you can customize, in your case check whether you element in another array or not
Why not just make your own piece of code / function?
foreach ($item in $attributes) {
foreach ($item2 in array('dog','cats','fishess')) {
// Check your custom functionality.
// Do something if needed.
}
}
You can take a look at array_intersect , but it is not going to check pattern matches (which you have somehow mentioned?)
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
foreach (array_intersects($attributes, array('dog','cats','fishess') {
// do something.
}
I would go with:
$patterns = array('/.*fish.*/', '/.*sharks.*/');
$subjects = array('fishing', 'aaaaa', 'sharkskin');
$matches = array();
preg_replace_callback(
$patterns,
function ($m) {
global $matches;
$matches[] = $m[0];
return $m[0];
},
$subjects
);
print_r($matches); // Array ( [0] => fishing [1] => sharkskin )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.