Strings
The management of strings is very important in any programming language;
there are several functions to manage strings, following is an explanation of the most widely used.
Strings can be created using single-quotes and double-quotes .
For example , both versions are correct and they produce the same result :
$string1 = "This is a test";
$string2 = 'This is a test';
A string can be displayed using echo :
echo $string1 ;
will display
This is a test
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.
$string=" this is "." a test ";
Most important string functions :
- strlen(string). returns number of characters inside the string including blank space. If you want blank space to be removed then you can apply string replace function str_replace to the string before applying strlen.
- split(separator,string). Divides a string into several, using a separation character.
- substr($string, $start, $end) : get a chunk of $string
echo substr('123456789', 0, 2);
Print 12 - str_repeat($string, $n) : repeat $string $n times
echo str_repeat('a', 10); does the same thing as for ($i = 0; $i < 10; $i++) {
echo 'a';
} - strrchr($string, $char) : find the last occurence of the character $char in $string
You can get the file extension from a file name. You can use this function in conjunction with substr().
$ext = substr(strrchr($filename, '.'), 1);
For example , we have test.php . strrchr($filename, '.') returns .php and substr(".php",1) returns php - trim($string) : remove extra spaces at the beginning and end of $string
- 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.
$string = 'Test1, 3 , 2005';
$info = explode(',', $string);
Variable $info is an array so we can access the values using $info[0], info[1] etc. For example $info[0]="Test1". - implode($string, $array) : Join the values of $array using $string
This one do the opposite than the previous function. - number_format($number): display a number with grouped thousands
echo number_format(15120777); displays display 15,120,777
admin – Thu, 2005 – 07 – 07 12:15