Script 14.1 Using preg_match()

Determine if a string is contained within another string.

Output

Test out some predefined patterns!

Source
<?php // Script 14.1 using regular expressions
// This script takes a submitted string and checks it against a submitted pattern.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	// Trim the strings:
	$pattern = trim($_POST['pattern']);
	$subject = trim($_POST['subject']);
			
	// Print the results:
	echo "<div id='message' class='message'><p style='text-align:center;'><b>$pattern</b><br />";
	// Test:
	if (preg_match ($pattern, $subject) ) {
		echo ' <span style="color:green;"><b>MATCHES</b></span> ';
	} else {
		echo ' <span class="error"><b>does NOT match</b></span> ';
	}	
	echo "<br/><b>$subject</b></p></div>";
}
?>
<form action="" method="post">
	<p id="description"></p>
	<p>
		<label for="p">Regex</label>
		<input id="p" type="text" name="pattern" value="<?php if (isset($pattern)) echo htmlentities($pattern); ?>" size="85" /> 
		
	</p>
	<p>
		<label for="s">Text</label>
		<input id="s" type="text" name="subject" value="<?php if (isset($subject)) echo htmlentities($subject); ?>" size="80" />
	</p>
	<p>
		<input type="submit" name="submit" value="Test!" />
	</p>
	<p>Test out some predefined patterns!
		<input type="button" name="zipcode" value="zipcode" onclick="fill_patterns(this.name)"/>
		<input type="button" name="telephone" value="telephone" onclick="fill_patterns(this.name)"/>
		<input type="button" name="password" value="password" onclick="fill_patterns(this.name)"/>
		<input type="button" name="email" value="email" onclick="fill_patterns(this.name)"/>
	</p>
</form>
<script type="text/javascript">
	function fill_patterns(pattern) {
		var patterns = {};
		patterns.zipcode = new Array(/^\d{5}(-\d{4})?$/,'<b>Standard US Zip code 12345-1234</b><br />(5 digits followed by an optional dash and 4 digit code.)');
		patterns.telephone = new Array(/^(\(?(\d{3})\)?\s?-?\s?(\d{3})\s?-?\s?(\d{4}))$/, '<b>Standard US phone number (111)123-1234 </b><br />(3 digit area code, optional parenthesis, 3 digits dash 4 digits.)');
		patterns.email = new Array(/^[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]{1,64}@([a-zA-Z0-9-])*(\.[a-zA-Z]{2,3})?\.[a-zA-Z]{1,4}$/, '<b>Generic email local-part@domain</b><br />(Email format is very difficult to properly match without extreme complexity - use at own risk.)');
		patterns.password = new Array(/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}$/, '<b>Test for password strength</b><br />Must be 6-18 characters long, must contain letters, underscores, hyphens, atleast one number and atleast one uppercase letter.');
		document.getElementById("p").value=patterns[pattern][0];
		document.getElementById("description").innerHTML=patterns[pattern][1];
		var element = document.getElementById("message");
		element.parentNode.removeChild(element);
	}
</script>