Script 14.3 Using preg_replace()

Replace a string within another string based on a regex pattern

Output

Modify some predefined patterns!

Source
<?php // Script 14.3 - replace.php
// This script takes a submitted string and checks it against a submitted pattern.
// This version replaces one value with another.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Trim the strings:
	$pattern = trim($_POST['pattern']);
	$subject = trim($_POST['subject']);
	$replace = trim($_POST['replace']);
			
	// Print the results:
	echo "<div id='message' class='message'><p>";
	
	// Check for a match:
	if (preg_match ($pattern, $subject) ) {
		echo '<span style="color:green;"><b>REPLACE</b></span><br/><span style="color:brown;"><b>'. $pattern .'</b></span> with <span style="color:brown;"><b>'. htmlspecialchars($replace).'</b></span>';
		echo '</p><p><b>Results</b><br/>'.str_replace( "\n", '<br />', preg_replace($pattern, $replace, $subject));
	} else {
		echo "The pattern $pattern was not found!";
	}	
	echo "</p><p><b>Original text</b><br/>".nl2br($subject)."</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="100" /> 		
	</p>
	<p>
		<label for="p">Replacement</label>
		<input id="r" type="text" name="replace" value="<?php if (isset($replace)) echo htmlentities($replace); ?>" size="100" /> 		
	</p>
	<p>
		<label for="s">Text</label>
		<textarea id="s" name="subject" rows="5" cols="80"><?php if (isset($subject)) echo htmlentities($subject); ?></textarea>
	</p>
	<p>
		<input type="submit" name="submit" value="Test!" />
	</p>
	<p>Modify 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)"/>
		<input type="button" name="word" value="word" onclick="fill_patterns(this.name)"/>
		<input type="button" name="curse" value="curse" onclick="fill_patterns(this.name)"/>
		<input type="hidden" name="predefined" value="" id="predefined"/>
	</p>
</form>
<script type="text/javascript">
	function fill_patterns(pattern) {
		var patterns = {};
		patterns.zipcode = new Array(/^\d{5}(-\d{4})?\r?$/m,
			'<b>Standard US Zip code 12345-1234</b><br />(5 digits followed by an optional dash and 4 digit code.)',
			'02145\n12345-1234\n54\n6565656\n111-2356',
			'You live in $0');
		patterns.telephone = new Array(/^(\(?(\d{3})\)?\s?-?\s?(\d{3})\s?-?\s?(\d{4}))\r?$/m,
			'<b>Standard US phone number (111)123-1234 </b><br />(3 digit area code, optional parenthesis, 3 digits dash 4 digits.)',
			'617-666-evil\n(111)-555 - 6568\n123-456-7890\n(789)123-5656',
			'');
		patterns.email = new Array(/^[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]{1,64}@([a-zA-Z0-9-])*(\.[a-zA-Z]{2,3})?\.[a-zA-Z]{2,4}\r?$/m, 
			'<b>Generic email local-part@domain</b><br />(Email format is very difficult to properly match without extreme complexity - use at own risk.)',
			'test12_new@hostmail.com\n123@24hours.net\nnews@BBC.uk.com\nnotan email!@wx.com\njunk$$@ace-movers.biz',
			'<a href="mailto:$0">$0</a>');
		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,}\r?$/m, 
			'<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.',
			'123456789_abc\nA_long_numb3r\nn3vErEnuff\n8789yyyuu98&6-W',
			'********');
		patterns.word = new Array(/\b[a-z]*for[a-z]*\b/,
			'Find a word that has a substring nested within.',
			'This is a formulaic test for informal matches, therefor conformation.',
			'_');
		patterns.curse = new Array(/\b((swear)|(darn)|(curse))[a-z]*\b/,
			'Find and replace the curse words "darn, swear, curse" with asterisks.',
			'Gosh darnit, I swear this morning has been cursed.',
			'*bleep*');
		document.getElementById("p").value=patterns[pattern][0];
		document.getElementById("description").innerHTML=patterns[pattern][1];
		document.getElementById("s").value=patterns[pattern][2];
		document.getElementById("r").value=patterns[pattern][3];
		document.getElementById("predefined").value=pattern;
		var element = document.getElementById("message");
		element.parentNode.removeChild(element);
	}
</script>