php - Splitting string into chunks by applying some rules -


i want split abc49.99ab55.5def89de7 chunks result (or similar) below. note: abc, ab, def , de allowed. numbers can float.

ideally this:

array (     [abc] => 49.99     [ab] => 55.5     [def] => 89     [de] => 7 ) 

this fine too:

array (     [0] => abc49.99     [1] => ab55.5     [2] => def89     [3] => de7 ) 

after seeing examples, i've come examples below unfortunately cannot enhance them meet needs defined above. please in matter?

1

preg_match('/(?<fo>abc|ab)?(?<fn>\d*\.?\d*)(?<so>def|de)?(?<sn>\d*\.?\d*)?/', 'abc49.99ab55.5def89de7', $matches);  array (     [0] => abc49.99     [fo] => abc     [1] => abc     [fn] => 49.99     [2] => 49.99     [so] =>      [3] =>      [sn] =>      [4] =>  ) 

2

preg_match_all('~^(.*?)(\d+)~m', 'abc49.99ab55.5def89de7', $matches);  array (     [0] => array         (             [0] => abc49         )      [1] => array         (             [0] => abc         )      [2] => array         (             [0] => 49         )  ) 

as op's request. should work you:

<?php      $str = "abc49.99ab55.5def89de7";     $arr = preg_split("/(?<=[0-9])(?=[a-z])/i", $str);     print_r($arr);  ?> 

regex explanation:

/(?<=[0-9])(?=[a-z])/i 
  • (?<=[0-9]) positive lookbehind - assert regex below can matched
    • [0-9] match single character present in list below
      • 0-9 single character in range between 0 , 9
  • (?=[a-z]) positive lookahead - assert regex below can matched
    • [a-z] match single character present in list below
      • a-z single character in range between , z (case insensitive)

flags:

  • i modifier: insensitive. case insensitive match (ignores case of [a-za-z])

Comments