I have an array built from the URL of a webpage.
If an item in that array contains the ?
symbol (The question mark symbol) then I want to remove that item from the array.
$array = ['news', 'artical', '?mailchimp=1'];
How could I do this? I've seen many examples where the searched string is the whole value, but not where it's just a single character or just part of the value.
http://www.php.net/manual/en/function.array-filter.php
function myFilter($string) {
return strpos($string, '?') === false;
}
$newArray = array_filter($array, 'myFilter');
foreach($array as $key => $one) {
if(strpos($one, '?') !== false)
unset($array[$key]);
}
Use a closure...
$array = array_filter($array, function($value){
if (strstr($value, '?') !== false)
{
return false;
}
return true;
});
From PHP8, you can make calls of str_contain()
inside array_filter()
and invert its boolean return value.
Code: ( Demo )
$array = ['news', 'artical', '?mailchimp=1'];
var_export(
array_filter(
$array,
fn($v) => !str_contains($v, '?')
)
);
The above will keep the original keys, so if you need to guarantee that your result array is indexed, just call array_values()
.
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.