preg_match to match substring of three numbers consecutively?

天大地大妈咪最大 提交于 2019-12-25 18:39:52

问题


I have a string $text_arr="101104105106109111112113114116117120122123124" fairly big string

If i want to split three numbers from them like 101,104,105 and store them in $array .What should i do?

I tried doing this:

preg_match_all('/[0-9]{3}$/',"$text_arr",$array); 

回答1:


The easiest way to do this is with preg_split()Docs:

$result = preg_split('/(\d{3})/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

See it working, or the result:

Array
(
    [0] => 101
    [1] => 104
    [2] => 105
    [3] => 106
    [4] => 109
    [5] => 111
    [6] => 112
    [7] => 113
    [8] => 114
    [9] => 116
    [10] => 117
    [11] => 120
    [12] => 122
    [13] => 123
    [14] => 124
)



回答2:


Though you could use a regular expression for this, it might be more performant to use a simple, standard function:

$groups = str_split($numbers, 3);//returns array you want

Read all about it here




回答3:


You have to remove the ends with $ from your expression, it is causing to return only one result

try like this

preg_match_all('/[0-9]{3}/', $text_arr, $array); 

check this working here




回答4:


Choose this simplest code

<?php
    $string = "101104105106109111112113114116117120122123124";
    $parts = str_split($string, 3);
    $res=implode(',',$parts);
    echo($res);
?>


来源:https://stackoverflow.com/questions/14100965/preg-match-to-match-substring-of-three-numbers-consecutively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!