5

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.

1
  • Is preg_split('/(?=\d)/', $input, 2) what you are looking for? Commented May 23, 2013 at 9:06

3 Answers 3

7

Try this:

<?php 

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

?>

Will output:

Array ( [0] => abc [1] => 2 2mg ) 
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

You don't need regular expressions for that:

$str = 'cream 100g';

$p = strcspn($str, '0123456789');
$before = substr($str, 0, $p);
$after = substr($str, $p);

echo "before: $before, after: $after";

See also: strcspn()

Returns the length of the initial segment of $str which does not contain any of the characters in '0123456789', aka digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.