Some Built In Functions for Strings

 

Introduction.  In order to improve our overall functionality we need to learn about some of the functions that are all provided with PHP.  This also will help motivate you to learn to develop your own functions.

We'll make use of some simple forms and then process the user inputs in a processing script page.  The built in functions that we will make use of are listed in the following table.  There are many more.

 

Function Description
trim($string) Trim any leading or trailing blanks.
strLen($string) This function returns the length of the string including blanks.
strtok($string, "char") This function breaks apart a string from the beginning up to where a particular "char" appears.
substr($string, n1, n2) This function returns the substring from the n1 through the n2 position.

 

Again, there are many other functions and you should checdk out some other references.

In order to allow the user to generate the inputs we will first make a form page called string_form.html.

 

<html>
<head>
<title>HTML Form</title>
</head>

<body bgcolor = "660000" text="cccccc">
<form action="handle_string_form.php" method=post>
<table>
<tr>
<td><font size = 4 color=cccccc>First Name:</font>
</td>
<td><input type=text name="txtFirstName" size=20>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Last Name:</font>
</td>
<td><input type=text name="txtLastName" size=20>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit name="submit" value="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

 

The form will look like the following.

 

 

 

The processing script should be called handle_string_form.php in order for the post to work.

 

<html>
<head>
<title>Some Built In String Functions</title>
</head>

<body>
<?php
// obtaining the information from the form and trimming it
$txtFirstName = trim($txtFirstName);
$txtLastName = trim($txtLastName);
print "Your first name after trimming is <b>$txtFirstName </b><BR>\n";
print "Your last name after trimming is <b>$txtLastName </b><BR>\n";
$Name = $txtFirstName . " " . $txtLastName;
print "Concatenating your first and last names gives <b>$Name </b><BR>\n";
$AlphaName = $txtLastName . ", " . $txtFirstName;
print "Concatenating your names into a form for listing gives <b>$AlphaName </b><BR>\n";
$LengthName = strLen($Name);
print "The number of characters, counting blanks, in your name is <b>$LengthName </b><BR>\n";
$tokenized_space = strtok($Name, " ");
print "Tokenizing your name on a blank gives <b>$tokenized_space </b><BR>\n";
$tokenized_comma = strtok($AlphaName, ",");
print "Tokenizing your list name on a comma gives <b>$tokenized_comma </b><BR>\n";
$substring_name = substr($AlphaName, 3, 8);
print "The 4th through 9th characters in your list name are <b>$substring_name </b><BR>\n";
?>
</body>
</html>

 

The results of this processing on the two strings "effulgent" and "efelantic" are contained in the following image.