Some Important String Functions

In this lesson, you will learn how to format strings and work with functions to manipulate them. You will also learn the benefits and dangers of magic quotes.

String Manipulation Functions

Trimming Strings
FunctionDescription
trim()Removes whitespace at beginning and end of a string.
ltrim()Removes whitespace at the beginning of a string.
rtrim()Removes whitespace at the end of a string.

Presentation
FunctionDescription
htmlentities()Escapes all HTML entities.
nl2br()Inserts a <br /> tag before each newline character in a string.
strtoupper()Converts a string to uppercase.
strtolower()Converts a string to lowercase.
ucfirst()Converts the first character of a string to uppercase.
ucwords()Converts the first character of each word in a string to uppercase.

Converting Strings and Arrays
FunctionDescription
explode()Splits a string into an array on a specified character or group of characters.
implode()Converts an array into a string, placing a specified character or group of characters between each array element.
join()Same as implode().

Substrings
FunctionDescription
substr(str,pos)Returns the substring from the character in position pos to the end of the string.
substr(str,-len)Returns the substring from len characters from the end of the string to the end of the string.
substr(str,pos,len)Returns a len length substring beginning with the character in position pos.
substr(str,pos,-len)Returns a substring beginning with the character in position pos and chopping off the last len characters of the string.
strstr(haystack,needle,before_needle)If the third argument (before_needle) is false (default), then it returns the part of the haystack from the needle on.

If the third argument (before_needle) is true, then it returns the part of the haystack before the needle.

The needle can be a string or an integer (or a number that can be converted to an integer).

stristr(haystack,needle,before_needle)Same as strstr(), but case insensitive.
strpos(haystack,needle)Finds the position of the first occurrence of a specified needle in a haystack (string).

The needle can be a string or an integer (or a number that can be converted to an integer).

strrpos(haystack,needle)Finds the position of the last occurrence of a specified needle in a haystack (string).

The needle can be a string or an integer (or a number that can be converted to an integer).

str_replace()Replaces all occurrences of one string with another string.

Comparing Strings
FunctionDescription
strcmp()Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than str2, and 0 if they are equal.
strcasecmp()Like strcmp() but case insensitive.
strlen()Returns the length of a string.

Concatenation

Concatenation is a programming word for adding strings together. In PHP, the concatenation operator is a dot (.). Generally, concatenation is used to combine literal text with variables or values returned from functions. The example below illustrates this.

<?php
$firstName = 'Paul';
$greeting = 'Hello';
echo $greeting . ' ' . $firstName . '!';
?>
<h2>Using Double Quotes to Avoid the Concatenation Operator</h2>
<?php
echo "$greeting $firstName!";
?>
<h2>Double quotes don't work when concatenating
the results of a function call</h2>
<?php
echo $greeting . ' ' . $firstName . '! Today is ' . date('l') . '.';
?>  

As shown in the code, double quotes can be used to avoid using the concatenation operator. This works for concatenating literal strings with variables, but it does not work for concatenating values returned from functions. To do that, the function call must be outside of any quotes and combined with the rest of the string using the concatenation operator. This also is demonstrated in the code sample above.

Counting number of words in a string?

To count number of words in a string you can use the str_word_count() function. This function has three parameters. The first parameters is the string to be checked. The second optional parameter is the value that should be returned. And the third optional parameters is to specify a special character to be considered as words.

By default, when no $return parameter is specified this function will return the number of words in the string. This is equal to pass 0 as the $return parameter. If you want this function to return the words found in the string as an array you can pass 1 as the $return parameter. Passing 2 as the $return parameter has also returned an array, but the array key is the position of the word in the string.

If we want to include special characters to be considered as words we can pass it using the third parameter. For example, in the last part of the code snippet below, we add the & character to be considered as a word.

<?php
$str = "The quick brown fox jumps over the lazy dog & cat.";

//
// Count the number of words in string $str.
//
$count = str_word_count($str);
echo "The number of words in \$str = $count words.\n";

//
// Count the words an return it as array.
//
$words = str_word_count($str, 1);
print_r($words);

//
// Count the words, return it as array with the position of word
// in the string as the array key.
//
$words = str_word_count($str, 2);
print_r($words);

//
// Count the words. The "&" character also considered as a word.
//
$words = str_word_count($str, 2, "&");
print_r($words);

Here is the result:

The number of words in $str = 10 words.
Array
(
[0] => The
[1] => quick
[2] => brown
[3] => fox
[4] => jumps
[5] => over
[6] => the
[7] => lazy
[8] => dog
[9] => cat
)
Array
(
[0] => The
[4] => quick
[10] => brown
[16] => fox
[20] => jumps
[26] => over
[31] => the
[35] => lazy
[40] => dog
[46] => cat
)
Array
(
[0] => The
[4] => quick
[10] => brown
[16] => fox
[20] => jumps
[26] => over
[31] => the
[35] => lazy
[40] => dog
[44] => &
[46] => cat
)

Randomly shuffling characters of a string

To randomly shuffle all characters of a string you can use the str_shuffle() function. This function takes a string as the parameter and produce a randomly shuffled version of the string.

<?php
$str = "Hello, World!. My name is PHP.";

//
// Shuffle the string randomly.
//
$shuffle = str_shuffle($str);

print "Original Text: $str.\n";
print "Shuffled Text: $shuffle."; 

This code snippet for example can produce the following output:

Original Text: Hello, World!. My name is PHP..
Shuffled Text: lH,y.Wd!en oaP oHm .eMPsli lr.

Removing non ASCII characters from a string

In the following code snippet you’ll see how to remove non ASCII characters from a string. The $str variable below contains some non ASCII characters. Because we don’t want this character to be there we’ll remove it. We’ll use a regular expression to do this using the preg_replace () function.

As you can see below the regex simply means that we what to remove the characters that doesn’t belong in the range of x20..x7E ASCII characters. But we also want to keep the linefeed \n (x0A) and the carriage return \r (x0D). You can learn more about ASCII code here: ASCII Table.

<?php
$str = 'Thïs ìs ä
string.';

//
// Replace characters where the ASCII code outside of x20..x7E.
//
$str = preg_replace('/[^\x0A\x0D\x20-\x7E]/', '', $str);

echo $str;  

The code snippet will output these lines:

Ths s
string.

Converting string into date in PHP

To convert a string representation of a date information into date in PHP we can use the combination of strtotime() and date() functions. The first step is to convert the string into timestamp using the strtotime() function. After having the timestamp we can pass it to the date() function with the corresponding date format to get the date.

Let’s see the code snippet below:

<?php
//
// A string of date.
//
$newYear = "01 January 2013";

//
// Convert a string of date into timestamp.
//
$timestamp = strtotime($newYear);

//
// Create a date from the timestamp and print out.
//
$date = date("Y-m-d", $timestamp);
echo "New Year: $date.\n"; 

Counting substring occurrences in string

If you want to count the occurrences of a substring in a string you can use the substr_count() function. This function will return the number of substrings found in the string. The first parameter is the string to be checked and the second parameter is the substring to be counted for its occurrences.

By default the search will start from the beginning of the string to the length of the string. If you want to search for the substring from a specific index in the string you can supply the $offset parameter and the maximum $length started from the offset you want to search.

You can see the example in the code snippet below:

<?php
$str = "The quick brown fox jumps over the lazy dog.";

//
// Count for substring "the"
//
$word = "the";
$count = substr_count(strtolower($str), $word);
echo "Occurrences of '$word': $count\n";

//
// Count for substring "o"
//
$char = "o";
$count = substr_count(strtolower($str), $char);
echo "Occurrences of '$char' : $count\n";

//
// Counting for substring "o" start from offset 15 to the end of
// the string.
//
$offset = 15;
$length = strlen($str) - $offset;
$count = substr_count(strtolower($str), $char, $offset, $length);
echo "Occurrences of '$char' from $offset to $length : $count\n"; 

This code snippet will produce the following result:

Occurrences of ‘the’: 2
Occurrences of ‘o’ : 4
Occurrences of ‘o’ from 15 to 29 : 3

Comparing two strings in PHP

To compare two strings for its content equality, we can use the strcmp() or strcasecmp() functions. The strcmp() compares two strings in case-sensitive. Which means the lowercase 'a' is not equal to the uppercase 'A'. While the strcasecmp() compares two strings and ignoring their case.

Both of this function returns an integer number. If the value returned is less than 0 is the $str1 is less than $str2. If the value returned is greater than 0 it means that $str1 is greater than $str2. When the returned value is 0 both strings are considered equals to each other.

Let’s see a code example below:

<?php
$str1 = "Hello";
$str2 = "hello";

//
// Compare two string in case-sensitive.
//
if (strcmp($str1, $str2) == 0) {
echo "'$str1' is equal to '$str2'.\n";
} else {
echo "'$str1' is not equal to '$str2'.\n";
}

//
// Compare two strings in case-insensitive
//
if (strcasecmp($str1, $str2) == 0) {
echo "'$str1' is equal to '$str2'.\n";
} else {
echo "'$str1' is not equal to '$str2'.\n";
}  

The first if, which uses the strcmp() function will print the following output:
‘Hello’ is not equal to ‘hello’.

And the second if, which uses the strcasecmp() function will print the following output:
‘Hello’ is equal to ‘hello’.

Calculating MD5 hash of a string

The calculate the MD5 hash of a string we can use the md5 function. The code snippet below shows you how to get the MD5 hash of the word secret.

<?php
$password = "secret";

//
// Calculate the md5 hash of the string "secret".
//
$md5 = md5($password);
echo "The md5 of $password is $md5\n";  

The hash for the string secret is:

The md5 hash of secret is ‘5ebe2294ecd0e0f08eab7690d2a6ee69’

Splitting a string using delimiter

In this example, you’ll see how to use the explode() functions to split a string using a delimiter. The first parameter to this function is the delimiter to be used to split the string. The second parameter is the string to be split. We can also define the limit for the explode function.

The limit can be a positive or a negative value. When the limit is set to a positive value the function will result in an array with the maximum length of the defined limit. The last array element will contains the rest of the string. If we set the limit to a negative value the explode() function will return all array elements except the last defined limit. If we define the limit to 0 it will return as a single element array.

Here is the example of the code snippet:

<?php
//
// Split the string by space.
//
$str = "The quick brown fox jumps over the lazy dog.";
$result = explode(" ", $str);
var_dump($result);

//
// Split the string by comma, and limit the result size to 5
// (a positive value) array elements. The last elements will
// contains the rest of the string.
//
$str = "a,b,c,d,e,f,g,h,i,j";
$result = explode(",", $str, 5);
var_dump($result);

//
// Split the string by pipe. A negative limit causes the explode
// function to return all elements except the last 3 value.
//
$str = "a|b|c|d|e|f|g|h|i|j";
$result = explode("|", $str, -3);
var_dump($result);

//
// Split the string by colon. A zero limit makes the explode function
// returns the original string.
//
$str = "a;b;c;d;e;f;g;h;i;j";
$result = explode("|", $str, 0);
var_dump($result);  

Here is the result of our code:

array(9) {
[0]=>
string(3) “The”
[1]=>
string(5) “quick”
[2]=>
string(5) “brown”
[3]=>
string(3) “fox”
[4]=>
string(5) “jumps”
[5]=>
string(4) “over”
[6]=>
string(3) “the”
[7]=>
string(4) “lazy”
[8]=>
string(4) “dog.”
}
array(5) {
[0]=>
string(1) “a”
[1]=>
string(1) “b”
[2]=>
string(1) “c”
[3]=>
string(1) “d”
[4]=>
string(11) “e,f,g,h,i,j”
}
array(7) {
[0]=>
string(1) “a”
[1]=>
string(1) “b”
[2]=>
string(1) “c”
[3]=>
string(1) “d”
[4]=>
string(1) “e”
[5]=>
string(1) “f”
[6]=>
string(1) “g”
}
array(1) {
[0]=>
string(19) “a;b;c;d;e;f;g;h;i;j”
}

Getting the length of a string

To get the length of a string we can use the strlen() function. This function will return the numbers of characters in the string. When the string is empty the strlen() function return 0. Let’s see the code snippet below:

 <?php
$str = "The quick brown fox jumps over the lazy dog.";

//
// Get the length of the $str string.
//
$length = strlen($str);
echo "Length = $length";  

Here is the result of our code:

Length = 44

Converting the case of a string

To convert the case of a string you can use the following functions: strtolower()strtoupper()ucfirst() and ucwords(). The strtolower() function converts a string to lowercase. The strtoupper() function converts a string to an uppercase. To convert the first letter of a string to uppercase we can use the ucfirst function. And if you want to convert the first letter of each word in a string you can use the ucwords() function.

Let’s now see the code snippet below as an example:

<?php
$str = "The quick brown fox jumps over the lazy dog";

//
// Convert a string to a lowercase.
//
echo "strtolower(): " . strtolower($str) . "\n";

//
// Convert a string to uppercase.
//
echo "strtoupper(): " . strtoupper($str) . "\n";

//
// Convert the first letter of the string to uppercase.
//
echo "ucfirst() : " . ucfirst($str) . "\n";

//
// Convert first letter of each word in string to uppercase.
//
echo "ucwords() : " . ucwords($str);  

And here are the result:

strtolower(): the quick brown fox jumps over the lazy dog
strtoupper(): THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
ucfirst() : The quick brown fox jumps over the lazy dog
ucwords() : The Quick Brown Fox Jumps Over The Lazy Dog<

Reversing a string by words

The following code snippet shows you how to reverse a string by words. We use three functions to get this functionality done. First, we use the preg_split() to split the string into an array of words. Second, we use the array_reverse() function to reverse the order of the array elements. Finally, we use the implode() function to join each element of the array to produce a single string.

 <?php
$str = "The quick brown fox jumps over the lazy dog";
$rev = reverseByWord($str);

echo "Original: $str\n";
echo "Reverse : $rev\n";

/**
* Reverse a string by words.
*
* @param $str string to be reversed.
* @return string the reversed string.
*/
function reverseByWord($str) {
return implode(" ", array_reverse(preg_split("/\s+/", $str)));
}  

When you run the code snippet you will get the following output printed:

Original: The quick brown fox jumps over the lazy dog
Reverse : dog lazy the over jumps fox brown quick The

Converting ASCII code into character

In this example, you’ll learn how to convert ASCII code into a character and vice versa. You can use functions such as chr()ord() or sprintf(). The chr() function takes an ASCII code as parameter and return the corresponding character. On the other side the ord() function takes in a character as parameter and return the ASCII code as the conversion result.

<?php
//
// Get the character for ASCII 65 which is the letter "A".
//
$ascii = 65;
$character = chr($ascii);
echo "ASCII $ascii representing the character '$character'.\n";

//
// Get the ASCII code for the letter "Z".
//
$character = "Z";
$ascii = ord($character);
echo "Character '$character' ASCII code is $ascii.\n";

//
// Get the letter for ASCII 97 using the sprintf function.
//
$ascii = 97;
$character = sprintf("%c", $ascii);
echo "ASCII $ascii representing the character '$character'.\n";  

Here is the result of our code snippet:

ASCII 65 representing the character ‘A’.
Character ‘Z’ ASCII code is 90.
ASCII 97 representing the character ‘a’.

Replacing a portion of text within a string

In the following code snippet you will learn how to replace a portion of text within a string. You can use the substr_replace function. This function takes parameters such as the string data to be replaced, the text replacement, start position and an optional length.

If the start parameter is a negative number the replacement will start from the end of the string data. If the length is not provided it will replace from the start until the end of the string.

<?php
$str = 'The quick brown fox jumps over the lazy dog.';
echo "Original : $str\n";

//
// Replace the brown color of the fox into yellow.
//
$result = substr_replace($str, 'yellow', 10, 5);
echo "Replacement: $result\n";

//
// Replace the word dog with cat.
//
$result = substr_replace($str, 'cat', -4, 3);
echo "Replacement: $result";  

The result of the above snippet is:

Original : The quick brown fox jumps over the lazy dog.
Replacement: The quick yellow fox jumps over the lazy dog.
Replacement: The quick brown fox jumps over the lazy cat.

Splitting a string into characters

In the following code snippet you will see how to split a string into characters. We have two options in this snippet. The first option is the use the [] operator. It allows us to access each character of the string at the specified index. In the code below we provide the indexes using for-loop.

The second option is to use the preg_split() function. We pass an empty regular expression of "//" to the function and it will split the string into an array of characters.

<?php
$str = "The quick brown fox jumps over the lazy dog.";

//
// Each character of the string can be accessed using the
// [] operator with the index of character to be read. To provide
// index we can use a for-loop
//
for ($i = 0; $i < strlen($str); $i++) {
echo $str[$i];
}
echo "\n";

//
// Read each character of a string using a regular expression
// function preg_split(). This will convert the string into an
// array of characters.
//
$chars = preg_split("//", $str);
for ($i = 0; $i < count($chars); $i++) {
echo $chars[$i];
}    

Splitting fixed length string using unpack

The code snippet below shows you how to split a fixed-length data using the unpack function. This function takes the data format and the string data. For example the expression of A10name means the unpack function read 10 character data from the string and stored in an associative array as name.

 <?php
//
// The fixed-length string to be splitted.
//
$str = "Alice 01/20/2000F1st Sunset Road Boulevard US80000";

//
// Define the data format and unpack the string data.
//
$format = 'A10name/A10dob/A1gender/A30address/A2country/A5zipcode';
$record = unpack($format, $str);

//
// Dumps the associative array information of the $record variable
//
var_dump($record);  

The snippet print out the following result:

array(6) {
[“name”]=>
string(5) “Alice”
[“dob”]=>
string(10) “01/20/2000”
[“gender”]=>
string(1) “F”
[“address”]=>
string(25) “1st Sunset Road Boulevard”
[“country”]=>
string(2) “US”
[“zipcode”]=>
string(5) “80000”
}

Finding position of first occurrence of a string

To find the position of first occurrence of a character or a word in a string we can use the strpos function. You need to pass the string to be searched and the character or word that you want to be found in the string.

<?php
$str = 'The quick brown fox jumps over the lazy dog.';

//
// Find the beginning index of the word jumps.
//
$index = strpos($str, 'jumps');
echo "Index : $index\n";

//
// Get a part of the string from the beginning until before the
// word jumps.
//
$copy = substr($str, 0, $index);
echo "Result: $copy";  

The code snippet will print the following output:

Index : 20
Result: The quick brown fox

Reading some part of a string

To get some part of a string we can utilize the substr function. This function can take three parameters. First parameter is the string from where the part of the string to be taken. The second parameter is the start index. And the third parameter is the length of the part to be taken.

The start index of a string begins at index 0. That means to get the word ‘The’ from the code snippet below, we must start the substring function to read from index 0. Index 1 will start from the ‘h’ character.

Let see some examples below:

<?php
$str = 'The quick brown fox jumps over the lazy dog.';

//
// Get a part of string from the 10th position to the end of
// the string. The index of a string start from 0.
//
$sub = substr($str, 10);
echo "Found: $sub\n";

//
// Get a part of string 'fox', starting at 16 position for 3
// characters
//
$sub = substr($str, 16, 3);
echo "Found: $sub\n";

//
// Get a part of string 'dog'. Using a negative value as the start
// will get substring n character from the end of the string.
//
$sub = substr($str, -4, 3);
echo "Found: $sub\n";

//
// Get substring from the 10th characters from the beginning up to
// the 10th characters from the end.
//
echo "Found: " . substr($str, 10, -10);   

The result of this code snippet are:

Found: brown fox jumps over the lazy dog.
Found: fox
Found: dog
Found: brown fox jumps over the

Magic Quotes

There are two settings in the php.ini file that determine how PHP handles incoming data. The settings are magic_quotes_gpc (on by default) and magic_quotes_runtime (off by default).

magic_quotes_gpc

The value of magic_quotes_gpc determines whether GET, POST and COOKIE data should be escaped “automagically”. If magic_quotes_gpc is set to 1, then single quotes, double quotes and backslashes will be escaped with backslashes. In this case, if a user entered “O’Reilly” as her last name, and your script returned that value to the browser (e.g, echo $_POST['LastName'];), the value returned would read “O\’Reilly”. You would need to strip the backslashes by passing the value through the stripslashes() function (e.g, echo stripslashes($_POST['LastName']);).

Although magic quotes can be useful, they can also cause confusion as the developer may not know whether magic quotes are turned on or off. To check whether they are on, use the get_magic_quotes_gpc() function as shown below.

if (get_magic_quotes_gpc())
{
    echo stripslashes($_POST['LastName']);
}
else
{
    echo $_POST['LastName'];
}

magic_quotes_runtime

The value of magic_quotes_runtime determines whether data returned from files and databases should be escaped “automagically”. It works similarly to magic_quotes_gpc.

Recommendation on Magic Quotes

Our recommendation on magic quotes is to turn them off in the php.ini file. You can easily escape a string when you need to with the addslashes() function.

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote