doukuibi9631 2017-10-14 22:46
浏览 27
已采纳

从字符串中保存数字

I'm looking to store all number's that occur alone in a string. The integers must occur on their own and be surrounded by white space.

Here's what I mean:

Input

blah 5 blah bl3h 555 blah 123 blah a2b3 5030a

Expected Output

[5], [555], [123]


Here's my attempted iterator that seems to group the current word correctly but adds nothing to the array

//$a = String
function numberReturn($a){

    $currWord;

    $numberArray = array();

    //Loop through string
    for($i = 0; $i < strlen($a); $i++){
        //Keep adding chars to current word
        $currWord .= $a[$i];


        //if white space check if current word is only numeric
        //if only numbers add it to array
        //when added, clear current word
        if(ctype_space($a[$i])){
            if(is_numeric($currWord)){
                $numberArray[] = $currWord;
            }
            $currWord = "";
        }
    }
    return $numberArray;
}
  • 写回答

2条回答 默认 最新

  • dtoaillwk759656786 2017-10-14 22:51
    关注

    Unless you specifically need to use a loop, you can explode on space and filter out every substring that isn't made of digits.

    $numbers = array_filter(explode(' ', $string), 'ctype_digit');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用