preg_split在第一个非数字字符处将字符串转换为数组

I have a string with some numbers and text and I'm trying to split the string at the first non-numeric character.

For Example, I have a few strings like

$value = '150px';
$value = '50em';
$value = '25%';

I've been trying to split the string using preg_split and a little regex.

$value_split = preg_split( '/[a-zA-Z]/' , $fd['yks-mc-form-padding'] );

I'm able to get the first part of the string using $value_split[0], for example I can store 150, or 50 or 25. I need to return the second part of the string as well (px, em or %).

How can I split the string using preg_split or something similar to return both parts of the array??

Thanks!

If you want to use regex and you haven't already, you should play with RegExr.

To do what you're wanting with regex, assuming all the strings will be all numeric together, followed by all non-numeric, you could do:

$matches = array();
preg_match('/([0-9]+)([^0-9]+)/',$value,$matches);

Then $matches[1] will be the numeric part and $matches[2] will be the rest

To break it down,
[0-9] matches any numeric character, so [0-9]+ matches 1 or more numeric characters in a row, so per the docs $matches[1] will have the (numeric) text matched in by the first set of parentheses

and [^0-9] matches any non-numeric character, so [^0-9]+ matches 1 or more non-numeric characters in a row and fills $matches[2] because it's in the 2nd set of parentheses

By preg_split() you cannot achieve what are you trying to. It will delete the part of your string which separates the whole string (in this case it will be separated by character [a-zA-Z]). Use preg_match() (or preg_match_all()) function.

You can use this pattern:

/([0-9]+)([a-zA-Z%]+)/

See demo.

Use the PREG_SPLIT_OFFSET_CAPTURE flag - it will cause an array to be returned, with item [0] being the string matched, and item [1] its starting position in the original string. You can then use that info to extract the rest of the string by using ordinary sub-string functionality. Something along the lines of:

$values_split = preg_split( '/[a-zA-Z]/' , $fd['yks-mc-form-padding'] );
$position = $values_split[0][1]
$length = $values_split[0][0]
$startPos = $position + $length
$numToGet = lenght($input) - $startPos

$remainder = substr($inline, startPos, $numToGet)