Jump to content

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


dsaba

Recommended Posts

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

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?

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.