0

Using preg_split on PHP, I want to separate letters and numbers, and ignore others (symbols, tab, space, etc). For example:

"A/BC 1"     => array("A","BC","1")
"A1-BCD/2"   => array("A","1","BCD","2")
"A1BC23-45"  => array("A","1","BC","23","45"), not array("A1BC23","45")
"ABC###123"  => array("ABC","123")
"AB+C^12/34" => array("AB","C","12","34")

What pattern must be written?

Mawan
  • 113
  • 6
  • 1
    Possible duplicate of [How to separate letters and digits from a string in php](https://stackoverflow.com/questions/4311156/how-to-separate-letters-and-digits-from-a-string-in-php) –  Sep 04 '18 at 09:56

2 Answers2

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]);
}

Output:

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
)
Toto
  • 89,455
  • 62
  • 89
  • 125
  • So, I must use preg_match_all, not preg_split? Thank you. Excuse me, my knowledge about PHP functions is not good. – Mawan Sep 04 '18 at 10:53
  • @Mawan: It will be much more complex to do same think with preg_split. – Toto Sep 04 '18 at 11:21
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);
TsV
  • 629
  • 4
  • 7