1

If I have a string like: 10/10/12/12

I'm using:

$string = '10/10/12/12';
preg_match_all('/[0-9]+\/[0-9]+/', $string, $results);

This only seems to match 10/10, and 12/12. I also want to match 10/12. Is it because after the 10/10 is matched that is removed from the picture? So after the first match it'll only match things from /12/12?

If I want to match all 10/10, 10/12, 12/12, what should my regex look like? Thanks.

Edit: I did this

$arr = explode('/', $string);
$count = count($arr) - 1;
$newarr = array();
for ($i = 0; $i < $count; $i++)
{
    $newarr[] = $arr[$i].'/'.$arr[$i+1];
}

1 Answer 1

3

I'd advise not using regular expression. Instead you could for example first split on slash using explode. Then iterate over the parts, checking for two consecutive parts which both consist of only digits.


The reason why your regular expression doesn't work is because the match consumes the characters it matches. Searching for the next match starts from just after where the previous match ended.

If you really want to use regular expressions you can use a zero-width match such as a lookahead to avoid consuming the characters, and put a capturing match inside the lookahead.

'#[0-9]+/(?=([0-9]+))#'

See it working online: ideone

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I edited my post to show how I did it now. Is that what you meant? Seems to work.
@Joker: Yes. You didn't check if the parts are digits, but if you can assume they are then your code seems OK to me.
ATM it should be okay to avoid the digit check, but may consider doing it later just in case, thanks for showing the alternative regex too.
@Joker: I'm actually surprised that putting a capturing group inside a non-capturing group works. I learned something new, so thanks for the interesting question. :)

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.