[英]Remove element from array if string contains any of the characters
如果字符串包含任何字符,则从数组中删除元素。例如,下面是实际的数组。
array(1390) {
[0]=>
string(9) "Rs.52.68""
[1]=>
string(20) ""php code generator""
[2]=>
string(9) ""Rs.1.29""
[3]=>
string(21) ""php codes for login""
[4]=>
string(10) ""Rs.70.23""
}
我需要数组来删除所有以RS.
开头的元素RS.
预期结果
array(1390) {
[0]=>
string(20) ""php code generator""
[1]=>
string(21) ""php codes for login""
}
到目前为止我尝试了什么:
foreach($arr as $ll)
{
if (strpos($ll,'RS.') !== false) {
echo 'unwanted element';
}
从上面的代码我如何从数组中删除不需要的元素。
您可以在foreach
循环中获取$key
并在数组上使用unset()
:
foreach ($arr as $key => $ll) {
if (strpos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
请注意,这将不会删除任何项目,因为“RS”永远不会出现。 只有“Rs”。
这听起来像是array_filter
的工作。 它允许您指定可以执行任何您喜欢的测试的回调函数。 如果回调返回true,则返回结果数组中的值。 如果返回false,则过滤掉该值。
$arr = array_filter($arr,
function($item) {
return strpos($item, 'Rs.') === false;
});
Rs与RS不同,您希望使用stripos
而不是strpos
进行非区分大小写检查
foreach($arr as $key => $ll)
{
if (stripos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
或指出使用arrayfilter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.