Silly Strings (Part 2)

Posted on 25. Feb, 2010 by admin in Basics


Ah, so you thought you were all done with strings, huh? Think again. You will spend a good deal of coding time in larger projects manipulating and otherwise dealing with strings. They will become even more important as we move on in our tutorials. Let’s just go over some useful functions when dealing with strings.

The function strlen() let’s us find the character length of a string. We use it by putting the variable or string literal in-between the parentheses, producing an integer answer.


<?php
echo strlen("I am the cookie monster!");
?>

Output:

24

This concept will come in handy later when we do loops and if statements. The next function of strpos() finds the position of a word in a string. Again, this will come in handy later. So, let’s say we wanted to find out what character position the word cookie was in the string “I am the cookie monster!” Our code would look something like this:


<?php
echo strpos("I am the cookie monster!", "cookie");
?>

Output:

8

If you count the number of character spaces you may be going, “Whoa that isn’t right. It should be nine!” My dear PHP friend you are wrong. It is eight because the first position is zero (the ‘I’), not one. Also notice the comma I put between the two string literals. The information we put between the parentheses of a function are called arguments. With a comma we can separate the two arguments we pass to this particular function. The first being the string to search for the word, and the second being the string we want to search it for. Similar to the following: “strpos(argument one, argument two);” Each function has its own arguments, so it is different for each one.

The last string function we will play with in this tutorial is the strrev() function. It’s job is to reverse a string. It’s mostly used to help us find patterns, for example a palindrome.


<?php
//Reverse this string
echo strrev("I am the cookie monster!");
//Newline
echo "\n";

//Lets try a palindrome(phrase that's the
//same forwards and backwards)

echo strrev("a man a plan a canal panama");
?>

Outputs:

!retsnom eikooc eht ma I
amanap lanac a nalp a nam a

If you put in the correct spacing on the second line it still says “a man a plan a canal panama,” but the first line is still gibberish. Below are some other useful string functions I think you should know, and their usage.

  • str_repeat(string, number of times to repeat) – Repeats a string the specified number of times
  • str_replace(string to find, string to replace it, string) – Replaces a word or words in a specified string
  • str_shuffle(string) – Shuffles are the characters in a string
  • strtolower(string) -  Turns the string to all lowercase
  • strtoupper(string) – Turns the string to all uppercase

Practice makes perfect. Play with all those function for a few minutes, and have fun.