In this project, you create a script that uses comparison operators and functions to compare two strings entered by a user.
1. Create a new document in your text editor.
2. Type the < !DOCTYPE> declaration, < html> element, document head, and < body> element. Use the strict DTD and "Compare Strings" as the content of the < title> element.
3. Add the following text and elements to the document body:
< h1>Compare Strings< /h1>< hr/>
4. Add the following script section to the document body:
< ?php
?>
5. Add the following form to the end of the document body. The < input> elements include PHP code that fills in the values from the $_GET['first_string'] and $_GET[second_string] autoglobals, if they exist.
< form action="CompareStrings.php" method="get" enctype="application/x-www-form-urlencoded">
< p>First String < input type="text" name="first_string" size="20" value="< ?php if(!empty($_GET['first_string'])) echo $_GET['first_string'] ?>" />< /p>
< p>Second String < input type="text" name="second_string" size="20" value="< ?php if(!empty($_GET['second_string'])) echo $_GET['second_string'] ?>" />< /p>
< p>< input type="submit" value="Compare Strings" />
< /form>< hr />
6. Add the following if statement to the script section. If both the $_GET['first_string'] and $_GET[second_string] autoglobals are set, the statements in the if statement execute. The nested if statement uses the comparison operator (==) to determine if both strings are the same. If the strings are not the same, the else clause uses the similar_text() and levenshtein() functions to compare the strings.
if(isset($_GET['first_string']) && isset($_GET['second_string'])) {
$FirstString = $_GET['first_string'];
$SecondString = $_GET['second_string'];
if($FirstString == $SecondString)
echo "< p>Both strings are the same.< /p>";
else {
echo "< p>Both strings have "
. similar_text($FirstString, $SecondString)
. " character(s) in common.< br />";
echo "< p>You must change " . levenshtein($FirstString,
$SecondString) . " character(s) to make the strings the same.< br />";
}
}
7. Add to the end of the script section the following else clause, which executes if values are not assigned to both the $_GET['first_string'] and $_GET[second_string] autoglobals:
else
echo "< p>Enter two strings you want to compare.< /p>";
8. Save document as CompareStrings.php in the Projects directory for Chapter 5.
9. Open CompareStrings.php in your Web browser by entering the following URL: http://localhost/PHP_Projects/Chapter.05/Projects/CompareStrings.php. Test the form to see if it correctly compares strings.
10. Close your Web browser window.