Manipulating Strings with PHP

PHP provides many functions that will transform a string argument, subtly or radically, as you'll soon see.

Cleaning Up a String with trim(), ltrim(), and strip_tags()

When you acquire text from user input or an external file, you can't always be sure that you haven't also picked up white space at the beginning and end of your data. The TRim() function shaves any white space characters, including newlines, tabs, and spaces, from both the start and end of a string. It accepts the string to be modified, returning the cleaned-up version.

 <?php $text = "\t\tlots of room to breathe      "; echo "<pre>$text</pre>"; // prints "               lots of room to breathe      "; $text = trim($text); echo "<pre>$text</pre>"; // prints "lots of room to breathe"; ?> 

Of course this might be more work than you require. You might want to keep white space at the beginning of a string but remove it from the end. You can use PHP's rtrim() function exactly the same as you would use trim(). Only white space at the end of the string argument will be removed, however:

 <?php $text = "\t\tlots of room to breathe      "; echo "<pre>$text</pre>"; // prints "               lots of room to breathe      "; $text = rtrim($text); echo $test; // prints "               lots of room to breathe"; ?> 

PHP provides the ltrim() function to strip white space only from the beginning of a string. Once again, this is called with the string you want to transform and returns a new string, shorn of tabs, newlines, and spaces:

 <?php $text = "\t\tlots of room to breathe      "; echo "<pre>$text</pre>"; // prints "               lots of room to breathe      "; $text = ltrim($text); echo "<pre>$text</pre>"; // prints "lots of room to breathe      "; ?> 

It is not unusual to have to remove tags from a block of text in order to display it without any HTML formatting. PHP provides the strip_tags() function for this purpose. The strip_tags() function accepts two arguments: the text to transform, and an optional set of HTML tags that strip_tags() can leave in place. The tags in this list should not be separated by any characters.

 <?php $string = "<p>\"I <i>simply</i> will not have it,\" <br>said Mr Dean.</p><p><b>The end.</b></p>"; echo strip_tags($string, "<br><p>"); ?> 

In the previous code fragment, we create an HTML-formatted string. When we call strip_tags(), we pass it the $string variable and a list of exceptions. The result is that the <p> and <br> tags are left in place and all other tags are stripped out. Also, the matching tag for <p></p>is removed as well.

The output of this snippet is

 "I simply will not have it," said Mr Dean. The end. 

Note the italics and bold formatting are gone.

Replacing a Portion of a String Using substr_replace()

The substr_replace() function works similarly to the substr() function, except it allows you replace the portion of the string that you extract. The function requires three arguments: the string you are transforming, the text you want to add to it, and the starting index. It also accepts an optional length argument. The substr_replace() function finds the portion of a string specified by the starting index and length arguments, then replaces this portion with the string provided, and returns the entire transformed string.

In the following code fragment used to renew a user's membership code, we change its second two characters:

 <?php $membership = "mz04xyz"; $membership = substr_replace($membership, "05", 2, 2); echo "New membership number: $membership"; // prints "New membership number: mz05xyz" ?> 

The result of this code is that the old membership number, "mz04xyz", is transformed into the new membership number, "mz05xyz".

Replacing Substrings Using str_replace

The str_replace() function is used to replace all instances of a given string within another string. It requires three arguments: a search string, the replacement string, and the master string. The function returns the transformed string.

The following example uses str_replace() to change all references to 2004 to 2005 within a master string:

 <?php $string  = "Site contents copyright 2004. "; $string .= "The 2004 Guide to All Things Good in the World"; echo str_replace("2004","2005",$string); ?> 

The str_replace() function accepts arrays as well as strings for all of its arguments. This allows us to perform multiple search and replace operations on a subject string, and even on more than one subject string. Take the following snippet, for instance:

 <?php $source = array(     "The package which is at version 4.2 was released in 2003.",     "The year 2003 was an excellent time for PointyThing 4.2!"); $search  = array("4.2", "2003"); $replace = array("5.3", "2004"); $source = str_replace($search, $replace, $source); foreach($source as $str) {     echo "$str<br>"; } ?> 

The output is of this snippet is

 The package which is at version 5.3 was released in 2004. The year 2004 was an excellent time for PointyThing 5.3! 

When an array of strings is passed to str_replace() for its first and second arguments, it will attempt to switch each search string with its corresponding replace string, in the text to be transformed. When the third argument is an array, the str_replace() function will return an array of strings. The search and replace operation will have been executed upon each string in the array.

Converting Case

PHP provides several functions that allow you to convert the case of a string. Changing case is often useful for string comparisons. To get an uppercase version of a string, use the function strtoupper(). This function requires only the string that you want to convert and returns the converted string:

 <?php $membership = "mz05xyz"; $membership = strtoupper($membership); echo "$membership"; // prints "MZ05XYZ" ?> 

To convert a string to lowercase characters, use the strtolower() function. Once again, this function requires the string you want to convert, and returns a converted version:

 <?php $membership = "MZ05XYZ"; $membership = strtolower($membership); echo "$membership"; // prints "mz05xyz" ?> 

PHP also provides a case function that has a useful cosmetic purpose. The ucwords() function makes the first letter of every word in a string uppercase. In the following fragment, we make the first letter of every word in a user-submitted string uppercase:

 <?php $full_name = "violet elizabeth bott"; $full_name = ucwords($full_name); echo $full_name; // prints "Violet Elizabeth Bott" ?> 

Although this function makes the first letter of each word uppercase, it does not touch any other letters. So, if the user had had problems with her Shift key in the previous example and submitted VIolEt eLIZaBeTH bOTt, our approach would not have done much to fix the string. We would have ended up with VIolEt ELIZaBeTH BOTt, which isn't much of an improvement. We can deal with this by making the submitted string lowercase with the strtolower() function before invoking ucwords():

 <?php $full_name = "VIolEt eLIZaBeTH bOTt"; $full_name = ucwords(strtolower($full_name)); echo $full_name; // prints "Violet Elizabeth Bott" ?> 

Finally, the ucfirst() function will capitalize only the first letter in a string. In the following fragment, we capitalize the first letter in a user-submitted string:

 <?php $myString = "this is my string"; $myString = ucfirst($myString); echo $myString; // prints "This is my string" ?> 

Wrapping Text with wordwrap() and nl2br()

When you present plain text within a Web page, you are often faced with a problem in which new lines are not displayed and your text runs together into one big mess. The nl2br() function conveniently converts every new line into an HTML break. So

 <?php $string  = "one line\n"; $string .= "another line\n"; $string .= "a third for luck\n"; echo nl2br($string); ?> 

will output

 one line<br /> another line<br /> a third for luck<br /> 

Notice that the <br> tags are output in XHTML-compliant format (<br />).

The nl2br() function is great for maintaining newlines that are already in the text you are converting. Occasionally, you may wish to add arbitrary linebreaks in order to format a column of text. The wordwrap() function is perfect for this. wordwrap() requires one argument, the string to be transformed. By default, wordwrap() will wrap lines every 75 characters, and will use \n as its linebreak character. So, the code fragment

 <?php $string  = "Given a long line, wordwrap() is useful as a means of "; $string .= "breaking it into a column and thereby making it easier to read"; echo wordwrap($string); ?> 

would output

 Given a long line, wordwrap() is useful as a means of breaking it into a column and thereby making it easier to read 

Because the lines are broken with the character \n, the formatting will not show up in HTML code, of course. wordwrap() has two more optional arguments: a number representing the maximum number of characters per line, and a string representing the end of line string you would like to use. So, applying the function call

 echo wordwrap($string, 24, "<br>\n"); 

to our $string variable, our output would be

 Given a long line,<br> wordwrap() is useful as<br> a means of breaking it<br> into a column and<br> thereby making it easier<br> to read 

The wordwrap() function won't automatically break at your line limit if a word has more characters than the limit. You can, however, use an optional fourth argument to enforce this. The argument should be a positive integer. So, using wordwrap() in conjunction with the fourth argument, we can now wrap a string, even where it contains words that extend beyond the limit we are setting. This fragment

 <?php $string  = "As usual you will find me at"; $string .= "chat/eating_green_cheese/forum.php. Hope to see you there!"; echo wordwrap($string, 24, "<br>\n", 1); ?> 

will output

 As usual you will find<br> me at<br> http://www.witteringonab<br><br> een_cheese/forum.php.<br> Hope to see you there! 

instead of

 As usual you will find<br> me at<br> <br> Hope to see you there! 

Breaking Strings into Arrays with explode()

The delightfully named explode() function is similar in some ways to strtok(). But explode() will break up a string into an array, which you can then store, sort, or examine as you want. The explode() function requires two arguments: the delimiter string that you want to use to break up the source string and the source string itself. The function optionally accepts a third argument, which will determine the maximum number of pieces the string can be broken into. The delimiter string can include more than one character, all of which will form a single delimiter (unlike multiple delimiter characters passed to strtok(), each of which will be a delimiter in its own right). The following fragment breaks up a date and stores the result in an array:

 <?php $start_date = "2004-08-09"; $date_array = explode("-", $start_date); // $date[0] == "2004" // $date[1] == "08" // $date[2] == "09" ?> 

Now that your head is filled with PHP string functions, let's move on to date and time functions.

Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: