Consider the following:
700italic
regular
300bold
300bold900
All of those are different examples, only one of the rows will be executed per time.
Expected outcome:
// 700italic
array(
0 => 700
1 => itailc
)
// regular
array(
0 => regular
)
// 300bold
array(
0 => 300
1 => bold
)
// 300bold900
array(
0 => 300
1 => bold
2 => 900
)
I made the following:
(\d*)(\w*)
But it's not enough. It kinda works when i only have two "parts" (number|string or string|number) but if i add a third "segment" to it i wont work.
Any suggestions?
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
Use the re. split() method to split a string into text and number, e.g. my_list = re. split(r'(\d+)', my_str) .
Regex will work faster in execution, however Regex's compile time and setup time will be more in instance creation. But if you keep your regex object ready in the beginning, reusing same regex to do split will be faster.
You could use preg_split
instead. Then you can use lookarounds that match a position between a word an a letter:
$result = preg_split('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', $input);
Note that \w
matches digits (and underscores), too, in addition to letters.
The alternative (using a matching function) is to use preg_match_all
and match only digits or letters for every match:
preg_match_all('/\d+|[a-z]+/i', $input, $result);
Instead of captures you will now get a single match for every of the desired elements in the resulting array. But you only want the array in the end, so you don't really care where they come from.
Could use the PREG_SPLIT_DELIM_CAPTURE
flag.
Example:
<?php
$key= "group123425";
$pattern = "/(\d+)/";
$array = preg_split($pattern, $key, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
?>
Check this post as well.
You're looking for preg_split
:
preg_split(
'((\d+|\D+))', $subject, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
)
Demo
Or preg_match_all
:
preg_match_all('(\d+|\D+)', $test, $matches) && $matches = $matches[0];
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With