I am trying to print "1" if there are at least two of the same figure in the match, else 0.
What is wrong in the regex?
if ( max ( array_map ('strlen', preg_split('/([0-9])[^0-9]*\1/', "1 2 3 1 4") ) ) == 1 )
echo 1;
else
echo 0;
I am trying to print "1" if there are at least two of the same figure in the match, else 0.
What is wrong in the regex?
if ( max ( array_map ('strlen', preg_split('/([0-9])[^0-9]*\1/', "1 2 3 1 4") ) ) == 1 )
echo 1;
else
echo 0;
The [^0-9]* matches any number of NON-digit characters. So if there's another number, it will fail the match. Try replacing [^0-9]* with a simple .*, which will match digits or non-digits.
echo preg_match('/(?<=^|[^0-9])([0-9)+)(?=[^0-9]).*(?<=[^0-9])\1(?=[^0-9]|$)/', "1 2 3 1 4");
Will match for any repeated number in the sequence, and echo 1 if there is something repeated, 0 if not.
(Original version just looked for something repeated after each other, this matches repeated anywhere in the string)
Try the following code. It should print 1 when there is a repeat number.
if(0 == strlen(preg_replace('/.*([0-9]).+\1.*/', '', '1 2 3 1 5 4')))
echo 1;
else echo 0;
The regex /.*([0-9]).+\1.*/
will match a number and another number (with .+
or anything in between them).
Hope this helps.
Try a lookahead assertion. I use "The Regex Coach" whenever I'm trying to figure something out. It doesn't give you hints or anything, but it does give immediate feedback.
Test string: "1 2 3 1 4 3"
Regex: ([0-9])(?=.*\1)
Basically the ()'s around the [0-9] store the result, and the lookahead (?= matches .* - any character and then \1 - what was matched first (so it looks for any number and then looks ahead to see if that number occurs again)
This will match both "1" and "3"
I'm not quite sure if php supports lookaheads, but that's my take.