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.

 

Link to comment
Share on other sites

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

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.