如果字符串包含任何字符,则从数组中删除元素。例如,下面是实际的数组。
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.
开头的元素
预期成果
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