Jump to content

Match 6 digits in a row, no repeats in any of the digits


dsaba

Recommended Posts

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

Link to comment
Share on other sites

<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>

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.