Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: split string until first occurance of a number

i have string like

cream 100G
sup 5mg Children

i want to split it before the first occurrence of a digit. so the result should be

array(
    array('cream','100G'),
    array('sup','5mg Children')
);

can so one tell me how to create pattern for this ?

i tried

list($before, $after) = array_filter(array_map('trim',
            preg_split('/\b(\d+)\b/', $t->formula)), 'strlen');

but something went wrong.

like image 780
Zalaboza Avatar asked May 23 '13 09:05

Zalaboza


2 Answers

The regular expression solution would be to call preg_split as

preg_split('/(?=\d)/', $t->formula, 2)

The main point here is that you do not consume the digit used as the split delimiter by using positive lookahead instead of capturing it (so that it remains in $after) and that we ensure the split produces no more than two pieces by using the third argument.

like image 21
Jon Avatar answered Sep 27 '22 20:09

Jon


Try this:

<?php 

$first_string = "abc2 2mg";
print_r( preg_split('/(?=\d)/', $first_string, 2));

?>

Will output:

Array ( [0] => abc [1] => 2 2mg ) 
like image 172
Vijaya Pandey Avatar answered Sep 27 '22 22:09

Vijaya Pandey