dsaba Posted January 13, 2008 Share Posted January 13, 2008 These work for matching 6 digits in a row with none repeating, is there a shorter/better way to write it? ~(\d)(?!\1)(\d)(?!\1|\2)(\d)(?!\1|\2|\3)(\d)(?!\1|\2|\3|\4)(\d)(?!\1|\2|\3|\4|5)(\d)~ ~(?\d)(?!.*\1)){6}~ checked against: 123456 in PCRE Quote Link to comment Share on other sites More sharing options...
effigy Posted January 14, 2008 Share Posted January 14, 2008 <pre> <?php $tests = array( '1234567890', '1213456789', '1234561234', '1122334455', '0000000000', 'ab987654cd' ); function check_digits ($matches) { $unique_digits = array_fill_keys(str_split($matches[0]), 0); echo $matches[0], count($unique_digits) == 6 ? ' passed.' : ' failed.' ; echo '<br>'; return $matches[0]; } foreach ($tests as $test) { preg_replace_callback('/(\d{6})/', 'check_digits', $test); } ?> </pre> Quote Link to comment Share on other sites More sharing options...
dsaba Posted January 14, 2008 Author Share Posted January 14, 2008 is there a shorter/better way to write it? I thought "it" was understood to be the regex pattern. However, you responded with a non-regex solution below. $unique_digits = array_fill_keys(str_split($matches[0]), 0); I see this is the essence of your shorter/better solution. Its a great way to solve the problem, but not with regex. Regardless of this still, how/why is your non-regex solution a shorter/better way to do it? Quote Link to comment Share on other sites More sharing options...
effigy Posted January 14, 2008 Share Posted January 14, 2008 The ability of regular expressions to use callbacks extends their functionality. Using a pattern alone, no, I don't think there is an easier way of doing this because you cannot "expand" a back reference in a character class. In terms of benchmarks, I'm not sure that it is better; however, to me, it seems easier to understand and scale. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.