<html>
<head>
<title>Regex Test</title>
</head>
<body bgcolor=lightyellow>
<h1><center>Regex Test</center></h1>
<?php
error_reporting(0); #turn warning off
$string = $_POST['string']; #get HTML form entry fields
$regex = $_POST['regex'];
$repStr = $_POST['repStr'];
$case = $_POST['case'];
if ($_POST) #if data was collected in _POST array
validate();
display();
//=============================================================================
function validate()
{
global $string, $regex, $repStr, $case, $msg;
if ($string == '') {
$msg = 'error';
$string_error = '*';
}
if ($regex == '') {
$msg = 'error';
$regex_error = '*';
}
if ($msg == 'error') {
$msg = 'Please enter a string and a regex expression';
return;
}
// $slash = '\\'; //a single back slash
// $slash2 = '\\\\'; //2 back slashes
// $regex = str_replace($slash2,$slash,$regex); //http adds another \ get rid of it
if (! $repStr)
{
$ok = preg_match("/$regex/$case", $string, $matches); //test whether the regex is found
$msg = ($ok) ? "Regex expression found: " . implode($matches,', ')
: "Regex expression not found";
}
if ($repStr)
{
$string2 = preg_replace("/$regex/$case", $repStr, $string); //replace the regex with replacement str
$msg = $string2;
}
}
//=============================================================================
function display()
{
global $string, $regex, $repStr, $case, $msg;
if ($case == 'i') $case_checked = 'CHECKED';
print "<form method=POST action=$_SERVER[PHP_SELF]> \n"; //itself
print "<fieldset style='width:550px; height:150px; border-color:gold'> \n";
print "<legend>Test a 'regex' regular expression</legend> \n";
print "<table bgcolor=eeeeee width=550> \n";
print "<tr>";
print "<tr>";
print "<td><b>Enter any string <font color=red> $string_error </font>";
print "<td><input type=text name=string size=40 value='$string'> \n";
print "<tr>";
print "<td><b>Enter a regex... <font color=red> $regex_error </font>";
print "<td><input type=text name=regex size=40 value='$regex'> \n";
print "<tr>";
print "<td><b>Optional replace with";
print "<td><input type=text name=repStr size=40 value='$repStr'>\n";
print "<tr>";
print "<td><b>Case insensitive ";
print "<td><input type=checkbox name=case value='i' $case_checked> \n";
print "<tr>";
print "<td width=150>";
print " <input type=submit value=' Regex Test '>";
print "<td><input type=reset value=' Cancel '>";
print "</table> \n";
print "</fieldset> \n";
print "<br><font color=red> $msg </font>";
print "<br/> \n";
print "</form> \n";
}
?>
<?php include "../include.php"; ?> <!-- hyperlink to see the code -->
</body>
</html>