Simple web design, web development, information technology, & technical communication

Articles and resources for web developers and the average person. Topics include web development, web design, technical writing and communication, and all aspects of information technology.

String manipulation in PHP

Originally published on Saturday, October 8th, 2005

The ability to manipulate string variables in PHP is extremely helpful. This tutorial will outline some of the more common situations you’ll encounter when working with PHP string variables.

Review: what’s a string?

In PHP, and every other flavor of Web programming, a string is a variable contained between quotes with a literal value. For example, $number = “2” is a string variable, whereas $number = 2 is not. The first value is seen as text only, the latter as a numeric value. Simply put, a string is a text variable.

Working with PHP strings: setting the stage

For this tutorial, we need a string variable to work with. Since my Red Sox were promptly ousted in last night’s MLB Playoffs, we’ll use them as my whipping boy. Here’s our string:


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
?>

If we printed this variable (echo $string;) it would display:
The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?

Capitalize the first letter of every word in a PHP string

Let’s say we have a situation where we’re pulling information out of a database (maybe book titles or first names and last names) and we want to make sure the first letter of each word is capitalized. This is easily accomplished with the function ucwords().


<?php
$string ="The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
echo ucwords($string);
?>

This would print:
The Boston Red Sox Lost Because Of Poor Pitching, Bad Defense, And A Lack Of Offense. That Doesn’t Leave Much, Does It?

Capitalize every letter in a PHP string


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
echo strtoupper($string);
?>

Prints:
THE BOSTON RED SOX LOST BECAUSE OF POOR PITCHING, BAD DEFENSE, AND LACK OF OFFENSE. THAT DOESN’T LEAVE MUCH, DOES IT?

Note: capitalizing the first letter in every word or making an entire string uppercase can also be accomplished via CSS. I’ll cover this in a later article.

Make every letter in a PHP string lowercase

Very similar to the above example, except we use the PHP function strtolower() instead of strtoupper().


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
echo strtolower($string);
?>

Prints:
the boston red sox lost because of poor pitching, bad defense, and lack of offense. that doesn’t leave much, does it?

Note: this can also be accomplished via CSS.

Replace parts of a PHP string

We can also replace part of our string with an entirely different piece of text. Consider it PHP’s built in “Find and Replace” function. This is accomplished via the str_replace() function.


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
$newstring = str_replace("Boston Red Sox", "New York Yankees", $string );
echo $newstring;
?>

The str_replace() function takes 3 parameters. In my example, I used “Boston Red Sox,” “New York Yankees”, and $string. The first parameter is the piece of text you want to replace. The second is the text that will replace the original. The third parameter tells PHP what value to do the find and replace on (in this case, my original $string variable).

In the above example, echo $newstring will print:
The New York Yankees lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?

After Randy Johnson’s stellar pitching performance last night, it turns out this might actually be true before the end of the weekend. Red Sox and Yankee fans unite!

Return all data AFTER a given character/string

This is a tricky technique. By using the PHP function strstr() I can return every part of the string after a given character or characters that I specify. For example:


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
$newstring =strstr ($string, "Boston");
echo($newstring);
?>

I passed the strstr() function 2 parameters. The first is what variable to perform the string manipulation on ($string). The second is the cutoff point in the text (take everything after and including this point).

The output of $newstring would be:
Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?

I could also do:
$newstring =strstr ($string, "That");

Which would display:
That doesn’t leave much, does it?

Advanced: Return all data BEFORE a given character/string

I can also print all of the data that occurs before a certain character or string component occurs. This is an advanced technique that requires 2 functions: substr() and strpos(). Currently, my $string variable consists of two sentences. By using a clever combination of substr() and $strpos, I can cut off the entire second sentence, leaving me with only the first.


<?php
$string = "The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense. That doesn’t leave much, does it?";
$newstring = substr($string, 0, strpos($string, "."));
echo($newstring);
?>

This would print:
The Boston Red Sox lost because of poor pitching, bad defense, and a lack of offense

Further Reading

This is only a small dose of PHP string manipulation, but the examples shown are all ones that I’ve used personally. For a more complete list of PHP string functions and how to use them, check out the following websites.

11 Responses to “String manipulation in PHP”

  1. sage Says:

    handy info! thanks

  2. Hagai Helman Says:

    Very useful. Thnx!

  3. stefan Says:

    How would I remove any characters after the last occureance of a string pattern?

  4. P. from Weston MA Says:

    I’m trying to figure out how to take a larger string and extract everything from it that looks like a zip code.

  5. Malcolm Clark Says:

    Thanks for the info. I needed a fix for string manipulation and it was here.

  6. Ryan Says:

    Thanks! Very helpful

  7. Goran Says:

    You got a typo in your text.. strops() instead of strpos(). You got me puzzled for a second there :]

  8. Christopher Jason Says:

    Doh! Thanks Goran. At least it was in the middle of a sentence and not in the code snippet… That would have annoyed a few people.

  9. Ryan Says:

    Great article, def going to keep in favs. Also dugg it. :)

  10. Anonymous Says:

    To replace last character from a string,
    substr_replace($str,”",-1);

  11. Jason Says:

    Cheers :) Very useful! Delivered just what I was after for my site!

Add a Comment

You must be logged in to post a comment.

Categories

Stay Updated