Jump to content

[SOLVED] regular expression newbie, help please


gammaman

Recommended Posts

How would I code the following

a minimum of six characters with the first being a letter.  There must be at least one upper case letter,

one and only one number, and one and only one symbol (%,#,~).  I have never used regular expressions before so I am clueless as to how to do this.

 

<pre>
<?php

srand(time());
### Create character pool.
$pool = array_merge(
	range('a', 'z'),
	range('A', 'Z'),
	range(0, 9),
	array('%', '#', '~')
);
$pool_size = count($pool) - 1;

### Iterate through X tests.
echo '<table>';
for ($j = 0; $j < 2500; $j++) {
	### Create a data string.
	$data = '';
	$len = rand(1, 10);
	for ($i = 0; $i < $len; $i++) {
		$data .= $pool[rand(0, $pool_size)];
	}
	echo "<tr><td>$data</td><td>";
	### Verify.
	echo (
			### A minimum of six characters with the first being a letter.
			### At least one number and one symbol.
			preg_match('/\A[a-z](?=.*\d)(?=.*[%#~]).{5,}\z/i', $data) &&
			### One uppercase letter.
			preg_match('/[A-Z]/', $data) &&
			### One and only one number.
			!preg_match('/\d.*\d/', $data) &&
			### One and only one symbol (%,#,~)
			!preg_match('/[%#~].*[%#~]/', $data)
	) ? 'Valid' : 'Invalid';
	echo '</td></tr>';
}
echo '</table>';
?>
</pre>

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.