我正在创建一个SMS应用程序,以下代码应该:
如果这些条件都不满足,则应从数组中删除该数字。
因此以下数字有效:
07123456789,07123456790,07123456791,07123456792,07123456793,07123456794
但是以下不会(并且需要删除):
0801458,07855488,6695522214124514
$param["number"] = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
$number = explode(',', $param["number"]);
foreach($number as $num){
if (!substr_compare($num, "07", 0, 3, false)) {
unset($num);
}
elseif (substr_compare($num, "07", 0, 3, true)) {
if(strlen($num) == 11) {
$li .= "447" . substr($num, 2) . ',';
}
}
}
$il .= substr($li, 0, strlen($li)-1);
echo $il;
// $request = substr($request, 0, strlen($request)-1);
// return $n;
}
我还需要从结果中删除最后一个逗号。
任何帮助将不胜感激。
谢谢,
凯尔
答案 0 :(得分:2)
您可以构建一个有效数字的新数组,并在最后构建implode()。
$validNumbers = array();
foreach($number as $num){
if (!substr_compare($num, "07", 0, 3, false)) {
unset($num);
}
elseif (substr_compare($num, "07", 0, 3, true)) {
if(strlen($num) == 11) {
$validNumbers[] = "447" . substr($num, 2);
}
}
}
$il .= implode($validNumbers, ',');
答案 1 :(得分:1)
正则表达式应该:
preg_grep('/^07\d{9}$/', $number);
答案 2 :(得分:0)
您可以将数字转换为数组,对它们应用过滤器,然后将它们粘合在一起。像这样:
$numbers = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
$array = explode(',', $numbers);
$filteredArray = array_filter($array, create_function('$item',
'return strlen($item) == 11 && stripos($item, "07") === 0;'
));
echo implode(",", $filteredArray);
或者,如果您使用的是PHP 5.3,您可以编写相同的内容:
$numbers = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
$array = explode(',', $numbers);
$filteredArray = array_filter($array, function($item) {
return strlen($item) == 11 && stripos($item, "07") === 0;
});
echo implode(",", $filteredArray);
哪个更漂亮。两者都将输出:
07123456789,07123456790,07123456791,07123456792,07123456793,07123456794
进一步阅读:
PHP.net array_filter()
PHP.net create_function()
PHP.net Anonymous functions