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.
<?php
$fruit = 'jamblang';
echo "My favourite fruit is $fruit <br>";
echo 'I lied, actually I hate $fruit <br>';
echo "\r\n My first line \r\n and my second line <br>\r\n";
echo ' Though I use \r\n this string is still on one line <br>';
?>
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.
<?php
$quote1 = "Never insult Dumbledore " .
"in front
of me!";
$quote2 = "Nami,
you are
my nakama!";
echo $quote1 . "<br>";
echo $quote2;
?>
String Functions
substr($string, $start, $end) : get a chunk
of $string
<?php
// print '12'
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
times
For example if you want to print a series of ten asteriks ( * ) you can
do it with a for loop like this :
<?php
for ($i = 0; $i < 10; $i++) {
echo '*';
}
?>
Or you can go the easy way and do it like this :
<?php
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()
<?php
$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
<?php
// 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
<?php
// extract information from comma separated values
$csv = 'Uzumaki Naruto,15,Konoha Village';
$info = explode(',', $csv);
?>
Now, $info is an array with three values :
Array
(
[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 :
<?php
$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 :
<?php
// print ordered list of names in array
$names = array('Uchiha Sasuke', 'Haruno Sakura', 'Uzumaki Naruto', 'Kakashi');
echo '<ol><li>' . implode('</li><li>', $names)
. '</li></ol>';
?>
The result of that code is like an ordered list just like shown below
- Uchiha Sasuke
- Haruno Sakura
- Uzumaki Naruto
- 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
<?php
// display 15,120,777
echo number_format(15120777);
?>