[英]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.