How to Split a string every time it reaches 4 digits using regular expressions in php

Published on Author Code Father

Split a string every time it reaches 4 digits using regular expressions in php.

Want to useĀ preg_match_all:

$str = 'ABCDE1234ABCD1234ABCDEF1234';
preg_match_all('/[a-z]+[0-9]{4}/i', $str, $matches);
var_dump($matches);

Output:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(9) "ABCDE1234"
    [1]=>
    string(8) "ABCD1234"
    [2]=>
    string(10) "ABCDEF1234"}}
  

—————————————————/OR/————————————————-

Use the principle of contrast:

\D+\d{4}
# requires at least one non digit
# followed by exactly four digits

See a demo on regex101.com.


In PHP this would be:
<?php
$string = 'ABCDE1234ABCD1234ABCDEF1234';
$regex = '~\D+\d{4}~';
preg_match_all($regex, $string, $matches);
?>

See a demo on ideone.com.

Comments

comments

Categories PHP