4

This seems like it must be so simple, but regular expressions are extremely confusing to me. I am grabbing $_GET variables that will look like typeX, optionX, groupX, etc. where X equals any positive whole integer. I need to then split the string at the 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 wholly unfamiliar with regex patterns but ended up coming up with:

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

but it just removed the number from the end rather than split the string into two arrays as was shown by the result:

Array ( [0] => type )

Also, I am unsure as if this would further split the number ten into a one and a zero, which I don't want. I feel like this is probably a mind numbingly simple solution but I am spinning in circles here.

3 Answers 3

13

You should use the PREG_SPLIT_DELIM_CAPTURE flag to capture the group which you made the split on. Here's 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 several flags using the | "bitwise or" operator.

Output:

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

1 Comment

That worked a treat. I was playing with PREG_SPLIT_DELIM_CAPTURE earlier but must have done something incorrectly. Thank you!
2

Try this one:

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

PHP example code:

<?php
$str = 'test189';
$pattern = '/(\D+)(\d+)/';

$res = preg_match_all($pattern, $str, $matches);
var_dump($matches);

?>

Comments

1

Use preg_match with capturing parentheses:

<?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"
)

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.