Wednesday, July 7, 2010

04 - Playing With Strings

Strings are probably what you will use most in your PHP script. From concatenating, looking for patterns, trim, chop etc. So I guess it's a good idea to take a better look at this creature. We will also take a peek at some string functions that you might find useful for everyday coding.

Creating a string

To declare a string in PHP you can use double quotes ( " ) or single quotes ( ' ). There are some differences you need to know about using these two.

If you're using double-quoted strings variables will be expanded ( processed ). Special characters such as line feed ( \n ) and carriage return ( \r ) are expanded too. However, with single-quoted strings none of those thing happen. Take a look at the example below to see what I mean.

Note that browsers don't print newline characters ( \r and \n ) so when you open string.php take a look at the source and you will see the effect of these newline characters.

Example : string.php

Source code : string.phps
$fruit = 'jamblang';

echo "My favourite fruit is $fruit

echo 'I lied, actually I hate $fruit

echo "\r\n My first line \r\n and my second line

echo ' Though I use \r\n this string is still on one line


String Concatenation

To concat two strings you need the dot ( . ) operator so in case you have a long string and for the sake of readability you have to cut it into two you can do it just like the example below.

Actually if you need to write a loong string and you want to write it to multiple lines you don't need concat the strings. You can do it just like the second example below where $quote2 is split into three lines.

Example : concat.php

Source : concat.phps

"in front
of me!";

$quote2 = "Nami,

you are

my nakama!";

echo $quote1 . "

echo $quote2;


String Functions

substr($string, $start, $end) : get a chunk
of $string

echo substr('123456789', 0, 2);

// print '56789'

echo substr('123456789', 4);

// print '89'

echo substr('123456789', -2);

// print '456'

echo substr('123456789', 3, -4);


str_repeat($string, $n) : repeat $string $n

For example if you want to print a series of ten asteriks ( * ) you can do it with a for loop like this :
for ($i = 0; $i < 10; $i++) {

echo '*';



Or you can go the easy way and do it like this :

echo str_repeat('*', 10);


strrchr($string, $char) : find the last occurence of the character $char in $string

For example: you want to get the file extension from a file name. You can use this function in conjunction with substr()

$ext = substr(strrchr($filename, '.'), 1);


What the above code do is get a chunk of $filename starting from the last dot in $filename then get the substring of it starting from the second character ( index 1

To make things clearer suppose $filename is 'tutorial.php'. Using strrchr('tutorial.php', '.') yield '.php' and after substr('.php',
1) we get the file extension; 'php'

trim($string) : remove extra spaces at the beginning and end of $string

// print 'abc def'

echo trim('  abc def      ');


addslashes($string) : adding backslashes before characters that need to be quoted in $string

This function is usually used on form values before being used for database queries. You will see this function used a lot in this tutorial ( like this one ) so there's no need to present an example here.

explode($separator, $string) : Split $string
by $separator

This function is commonly used to extract values in a string which are separated by a a certain separator string. For example, suppose we have some information stored as comma separated values. To extract each values we ca do it like shown below

// extract information from comma separated values

$csv = 'Uzumaki Naruto,15,Konoha Village';

$info = explode(',', $csv);


Now, $info is an array with three values :



[0] => Uzumaki Naruto

[1] => 15

[2] => Konoha Village


We can further process this array like displaying them in a table, etc.

implode($string, $array) : Join the values of $array using $string

This one do the opposite than the previous function. For example to reverse
back the $info array into a string we can do
it like this :

$info = array('Uzumaki Naruto', 15, 'Konoha Village');

$csv = implode(',', $info);


Another example : Pretend we have an array containing some values and we want to print them in an ordered list. We can use the implode() like this :

// print ordered list of names in array

$names = array('Uchiha Sasuke', 'Haruno Sakura', 'Uzumaki Naruto', 'Kakashi');

echo '
  1. ' . implode('
  2. ', $names)
    . '


The result of that code is like an ordered list just like shown below

  1. Uchiha Sasuke

  2. Haruno Sakura

  3. Uzumaki Naruto

  4. Kakashi

By the way, i did write the above php code to print that list instead of writing the list directly

number_format($number): display a number with grouped thousands

When displaying numbers it's usuallly more readable if the numbers is properly formatted like 1,234,567 instead of 1234567. Using this function is very simple like shown below

// display 15,120,777

echo number_format(15120777);


No comments: