String Functions

A lot of functions can enhance a string’s capabilities. One very common need is to convert an integer into a string. This may happen when you take in an integer from a form and need to add it to part of a string. Fortunately, there is a function that can do this: strval(). Let’s put this in a quick program. Watch what happens if we have the user enter two numbers. The program adds them together and combines the results of strval(). The first page is a simple HTML page. The following code creates a page that looks like Figure 8.8:

Figure 8.8. The phpft08-03.html file.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
<title>Putting two numbers together with strval()</title>
</head>

<body>

<form name="together" action="phpft08-03.php" method="get">

       Enter your first number: <input type="text" name="firstop">
       <p>Enter your second number: <input type="text" name="secondop">
       <p><input type="submit">
</form>
</body>
</html>

Now, let’s take a look at the PHP document:

<html>
<head>
<title>Using strval()</title>
</head>
<body>
<?php

$a = $_GET['firstop'];
$b = $_GET['secondop'];

echo "Let's take a look at the two results of using your operators.";
echo "<p>Using the addition operator does this: ".( $a + $b);
echo "<br>Adding the numbers using strval produces this: ". strval($a).' '.
strval($b);
?>
</body>

</html>

This page, with the inputs of 13 and 15, looks like Figure 8.9.

Figure 8.9. The phpft08-03.php file.


You see what this program does? In the echoing section, adding two numbers creates an addition problem. However, using their strval() values, you get a new sentence!

This is only one of the possible string functions, and there are several dozen more. Some are really cool, such as substr(), which lets you search within a string, and soundex(), which lets you find words that have similar pronunciations. I recommend researching www.maneeshsethi.com and www.php.net to learn some more useful techniques for strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.160.154