Perl-compatible Regular Expression Functions

Contact Us or call 1-877-932-8228
Perl-compatible Regular Expression Functions

Perl-compatible Regular Expression Functions

preg_match()

The syntax for preg_match() is as follows.

preg_match(pattern, text_to_search);

preg_match() returns 1 if pattern is found in text_to_search and 0 if it is not.

preg_replace()

The syntax for preg_replace() is as follows.

preg_replace(pattern, replacement, text_to_search);

preg_replace() replaces all instances of pattern in text_to_search with replacement.

Regular Expression Tester

We have created a simple PHP-based regular expression tester. The code for the tester is shown below.

Code Sample:

RegExp/Demos/Tester.php
<?php
@$pattern = (get_magic_quotes_gpc()) ? stripslashes($_POST['Pattern']) : $_POST['Pattern'];
@$textToSearch = (get_magic_quotes_gpc()) ? stripslashes($_POST['TextToSearch']) : $_POST['TextToSearch'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
	<title>Regular Expression Tester</title>
<style>
	.big {font-family:Verdana; font-size: 14pt; font-weight:bold; color:darkblue; text-decoration:none; padding: 4px}
	.reg:hover {border: 2px solid red; padding: 2px}
</style>

<script>
function usePattern(PATTERN)
{
	document.formRE.Pattern.value=PATTERN;
	document.getElementById("display").innerHTML="<b>PATTERN: </b>" + PATTERN;
}
</script>
</head>

<body>
<h2>Regular Expression Tester</h2>
<form name="formRE" method="post">
<table>
<tr>
	<td align="right"><span class="big">Text to search:</span></td>
	<td><input type="text" name="TextToSearch" value="<?= $textToSearch ?>" size="50" maxlength="50"></td>
</tr>
<tr>
	<td align="right"><span class="big">Pattern:</span></td>
	<td><input type="text" name="Pattern" size="50" value="<?= $pattern ?>" maxlength="100"></td>
</tr>
<tr>
	<td colspan="2" align="center">Try these patterns:
		<a href="javascript:usePattern('/^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-\\.]+$/');">Email</a> |
		<a href="javascript:usePattern('/^[0-9]{3}[\\- ]?[0-9]{2}[\\- ]?[0-9]{4}$/');">SSN</a> |
		<a href="javascript:usePattern('/^\\(?[2-9][0-9]{2}\\)?[\\- ]?[0-9]{3}[\\- ]?[0-9]{4}$/');">Phone</a>
	</td>
</tr>
<tr>
	<td colspan="2" align="center" style="font-size:18pt; font-family:Arial, Helvetica, sans-serif; background: #cccccc;">
		<?php
			if (empty($pattern))
				echo '<span style="color:blue">Let\'s play!</span>';
			elseif (preg_match($pattern,$textToSearch))
				echo '<span style="color:green">Match</span>';
			else
				echo '<span style="color:red">No Match</span>';
		?>
	</td>
</tr>
<tr align="center">
<td colspan="2">
      <input type="submit" value="Submit">
      <input type="reset">
</td>
</tr>

</table>
</form>
<div id="display" style="font-size:18pt; font-family:Courier New"><b>PATTERN:</b> <?= $pattern ?></div>

</body>
</html>
Next