PHP:使用preg_split分隔字母和数字

时间:2018-09-04 09:02:54

标签: php regex

我要使用 PHP 上的 preg_split ,我要分隔字母和数字,并忽略其他字母和符号(符号,制表符,空格等)。 例如:

Matches

必须写什么模式?

2 个答案:

答案 0 :(得分:1)

$arr = [
"A/BC 1",
"A1-BCD/2",
"A1BC23-45",
"ABC***123",
"AB+C^12/34",
];
foreach ($arr as $ele) {
    preg_match_all('/[A-Z]+|\d+/', $ele, $m);
    print_r($m[0]);
}

输出:

Array
(
    [0] => A
    [1] => BC
    [2] => 1
)
Array
(
    [0] => A
    [1] => 1
    [2] => BCD
    [3] => 2
)
Array
(
    [0] => A
    [1] => 1
    [2] => BC
    [3] => 23
    [4] => 45
)
Array
(
    [0] => ABC
    [1] => 123
)
Array
(
    [0] => AB
    [1] => C
    [2] => 12
    [3] => 34
)

答案 1 :(得分:0)

    $str = "A/BC 1, A1-BCD/2, A1BC23-45, ABC***123, AB+C^12/34";
    $e = explode(',', $str);
    $arr = [];
    foreach ($e as $value){
        preg_match_all('/\w+/', $value, $matches);
        $s = '';
        foreach ($matches as $match){
            foreach ($match as $m){
                $s .= $m . " ";
            }
            $arr[] = $s;
        }

    }

    echo '<pre>';
    print_r($arr);