php - count particular permutations

56 views Asked by At

I have some strings that look like this :

431234412

What I am trying to do is find all the instances of '1234' in each string BUT the numbers can be used again so long as they are in order.

So for instance, in the above string there would be 2 instances of '1234' since '12344' can be interpreted as '1234-' or '123-4'.

I was thinking of writing recursive functions but maybe there is simple way to do with regex?

1

There are 1 answers

0
Beat On

The regex to do that is quite simple:

$subject= '431234412';
preg_match_all('/(1+2+3+4)+/', $subject, $matches);

You will find all occurrences in the array $matches.

The + behind each digit means, that this digit may be repeated.