How to blow a string with any integer? Regex?

It seems like it should be that simple, but regular expressions really confuse me. I grab the $ _GET variables, which will look like typeX, optionX, groupX, etc., where X is equal to any positive integer. I need to split the string into an integer so that type1 becomes an array of "type" and "1", however type10 must become an array of "type" and "10" not "type" and "1" and "0".

I am completely unfamiliar with regex patterns, but ended up with:

$array = preg_split("#\\d+#", $key, -1, PREG_SPLIT_NO_EMPTY); print_r($array); 

but he just removed the number from the end, and did not split the string into two arrays, as was shown as a result:

 Array ( [0] => type ) 

Also, I'm not sure, as if it would further divide the number ten into one and zero, which I don't want. I feel that this is probably just a mind-blowing decision, but I'm circling here.

+3
source share
3 answers

You must use the PREG_SPLIT_DELIM_CAPTURE flag to capture the group you are divided into. Here is an example:

 <?php $key= "group12"; $pattern = "/(\d+)/"; $array = preg_split($pattern, $key, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); print_r($array); ?> 

Note that you combine multiple flags with | bitwise or operator.

Output:

 Array ( [0] => group [1] => 12 ) 
+10
source

Try the following:

 /(\D+)(\d+)/ 

PHP code example:

 <?php $str = 'test189'; $pattern = '/(\D+)(\d+)/'; $res = preg_match_all($pattern, $str, $matches); var_dump($matches); ?> 
+1
source

Use preg_match with brackets:

 <?php $str = "type10"; $matches = array(); preg_match('/([a-zA-Z]+)(\d+)/', $str, $matches ); print_r($matches); ?> 

Outputs:

 Array( 0 => "type10" 1 => "type" 2 => "10" ) 

Then, to get rid of the first element:

 <?php array_shift($matches); print_r($matches); ?> 

To give:

 Array( 0 => "type" 1 => "10" ) 
+1
source

All Articles