PHP sports a massive string manipulation library, offering almost 100 native functions capable of dicing, splicing, parsing and searching text in every imaginable fashion. In fact, PHP's capabilities in this regard are so strong that it can sometimes be difficult to determine the best possible approach for accomplishing a particular string-related task. In this article I highlight the ideal solutions to 10 common string manipulation tasks.

1. Determining the Length of a String

This is by far the most obvious example demonstrated in this article, but the question of how to determine the length of a string comes up so often that I'd be remiss to neglect mentioning the strlen() function:
$text = "sunny day"; $count = strlen($text); // $count = 9

2. Truncating Text to Produce a Summary

News-oriented websites often produce summaries of recently published articles by truncating each article after the first 200 or so characters and adding an ellipsis at the end of the truncated string. You can achieve this effect using the substr_replace() function. For reasons of space I'll demonstrate this effect using a 40-character limit:
$article = "BREAKING NEWS: In ultimate irony, man bites dog."; $summary = substr_replace($article, "...", 40); // $summary = "BREAKING NEWS: In ultimate irony, man bi..."

3. Counting the Number of Characters and Words in a String

You'll often see blogs and news-oriented websites summarizing the total number of words in a given article, or requiring contributors to submit articles falling within a predefined range. You can report an article's size in terms of word count using the str_word_count() function:
$article = "BREAKING NEWS: In ultimate irony, man bites dog."; $wordCount = str_word_count($article); // $wordCount = 8
Sometimes you'll need to exert even tighter control over the amount of space used for contributions such as comments, tracking them to the character. If you'd like to know how many characters comprise a string, see the function count_chars().

4. Parsing a CSV File

Data is commonly stored in files using a comma-separated format (known as CSV format). CSV uses a comma or similar predefined delimiter character to separate each column comprising a row. You'll often create PHP scripts capable of importing this data and parsing or manipulating it to your needs. Over the years I've seen quite a few different approaches to parsing a CSV file, most notably using a combination of the fgets() and explode() functions to read and parse the file. However, the easiest solution involves using a function that isn't actually classified as part of PHP's string manipulation library: fgetcsv(). This function gives you the ability to exert greater control over both the delimiter character and any enclosure character used to formally delimit each string.
Consider the following CSV file:
1,John,Smith,Plumber 2,Mark,Seagal,Instructor 3,Peter,Haines,Writer
Using fopen() and fgetcsv(), we can easily parse this file to retrieve the first name of each contact:
$fh = fopen("contacts.csv", "r"); while($line = fgetcsv($fh, 1000, ",")) { echo "Contact: {$line[1]}
"; }

5. Converting an Array into a String

At some point, you will probably need to create CSV files as well as read from them, meaning you'll need to convert data into comma-delimited strings. If this data were initially retrieved from a database, it's likely to be made available to you as an array. You can convert an array to a comma-delimited string using the implode() function:
$csv = implode(",", $record);

6. Converting URLs into Hyperlinks

Many WYSIWYG editors provide toolbars, which allow users to markup text to include hyperlinks. However, you can easily automate this process when the content is rendered to the page, saving your contributors an inconvenient and occasionally error-prone additional step. To convert URLs into hyperlinks, you use the preg_replace() function, which can search a string according to a regular expression that defines the structure of a URL and replace all instances with updated text containing a hyperlinked URL:
$url = "W.J. Gilmore, LLC ("; $url = preg_replace("/http://([A-z0-9./-]+)/", "$0", $url); // $url = "W.J. Gilmore, LLC ("

7. Removing HTML Tags from a String

Ensuring that user input does not contain potentially hazardous characters, which could lead to SQL injection or cross-site scripting attacks, is one of the primary roles you play as a Web developer. The PHP language includes numerous security-related features that can help you scrub data, including the Filter extension. You might however wish to exercise a bit of additional control over user input rather than taking a "scorched earth" approach. For instance, you could allow users to include some basic HTML within their comments such as a tag. To do this, check out the strip_tags() function, which by default removes all HTML tags from a string, but also allows you to override the default and specify certain allowable tags. For instance, you can strip all tags except for the and using the following statement:
$text = strip_tags($input, "

8. Comparing Two Strings

Comparing two strings to ensure they are identical, such as a user's provided password and that user's confirmed password, is a common task. You can do so easily using the substr_compare() function:
$pswd = "secret"; $pswd2 = "secret"; if (! strcmp($pswd, $pswd2)) { echo "The passwords are not identical!"; }
If you'd like to compare two strings using a case-insensitive approach, see the function strcasecmp().

9. Converting Newline Characters to Break Tags

Earlier in this article I demonstrated how to save your users the hassle of explicitly creating hyperlinks by using the preg_replace() function to automatically convert URLs into hyperlinks. Continuing with that theme, you can automatically convert any newline characters into HTML tags using the nl2br() function:
$comment = nl2br($comment);

10. Applying Wordwrap

For formatting reasons many word processors, code editors, and websites wrap lines of text that surpass a certain character limit. You can carry out this task using PHP's wordwrap() function:
$speech = "Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."; echo wordwrap($speech, 30);
Executing this snippet produces the following output:
Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.


The functions highlighted here represent only a small portion of those available within PHP's string parsing library. Check out the PHP documentation for a complete list.

About the Author

Jason Gilmore is the founder of and the author of several popular books, including "Easy PHP Web sites with the Zend Framework" and "Beginning PHP and MySQL: From Novice to Professional" (currently in its third edition). Check out his new DZone reference card, titled "Getting Started with the Zend Framework."