PHP String Functions

PHP addslashes() Function +

Definition and Usage:

The addslashes() function returns a string with backslashes in front of predefined characters.

The predefined characters are:

single quote (')
double quote (")
backslash (\)
NULL

Tip: This function can be used to prepare a string for storage in a database and database queries.

Note: PHP runs addslashes() on all GET, POST, and COOKIE data by default. Therefore you should not use addslashes() on strings that have already been escaped, this will cause double escaping. The function get_magic_quotes_gpc() can be used to check this.

Syntax:

addslashes(string)

$str = "Who's Peter Griffin?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";

PHP stripslashes() Function +

Definition and Usage:

The stripslashes() function removes backslashes added by the addslashes() function.

Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

Syntax:

stripslashes(string)

echo stripslashes("Who\'s Peter Griffin?");

The output will be:
Who's Peter Griffin?

PHP strip_tags() Function+

Definition and Usage:

The strip_tags() function strips a string from HTML, XML, and PHP tags.

Note: HTML comments are always stripped. This cannot be changed with the allow parameter.

Note: This function is binary-safe.

Syntax:

strip_tags(string,allow)

echo strip_tags("Hello world!");

The output will be:
Hello world!

PHP chunk_split() Function +

Definition and Usage:

The chunk_split() function splits a string into a series of smaller parts.

Note: This function does not alter the original string.

Syntax:

chunk_split(string,length,end)

Split the string after each character and add a "." after each split:

$str = "Hello world!";
echo chunk_split($str,1,".");

The output will be:
H.e.l.l.o. .w.o.r.l.d.!.

PHP count_chars() Function+

Definition and Usage:

The count_chars() function returns information about characters used in a string (for example, how many times an ASCII character occurs in a string, or which characters that have been used or not been used in a string).

Syntax:

count_chars(string,mode)

The parameter "mode 3" will return a string with all the different characters used. In this example, the characters used in "Hello World!" are:

Return a string with all the different characters used in "Hello World!" (mode 3):

$str = "Hello World!";
echo count_chars($str,3);

The output is:
!HWdelor

PHP explode() Function+

Definition and Usage:

The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.

Note: This function is binary-safe.

Syntax:

explode(separator,string,limit)

separator	Required. Specifies where to break the string
string	    	Required. The string to split
limit	    	Optional. Specifies the number of array elements to return.
            	Possible values:

                    Greater than 0 - Returns an array with a maximum of limit element(s)
                    Less than 0 - Returns an array except for the last -limit elements()
                    0 - Returns an array with one element


Using the limit parameter to return a number of array elements:

$str = 'one,two,three,four';
$xxx = explode(',',$str);
echo $xxx[2];

The output is:
three

PHP implode() Function+

Definition and Usage:

The implode() function returns a string from the elements of an array.

Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.

Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.

Note: This function is binary-safe.

Syntax:

implode(separator,array)

Join array elements with a string:

$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);

The outpu is:
Hello World! Beautiful Day!
-----------------------------------------

$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."<br>";
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>"; 
echo implode("X",$arr);

The output is:
Hello World! Beautiful Day!
Hello+World!+Beautiful+Day!
Hello-World!-Beautiful-Day!
HelloXWorld!XBeautifulXDay!

The join() function is an alias of the implode() function.

PHP htmlspecialchars() Function+

Definition and Usage:

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >

Tip: To convert special HTML entities back to characters, use the htmlspecialchars_decode() function.

Syntax:

htmlspecialchars(string,flags,character-set,double_encode)

Convert the predefined characters "<" (less than) and ">" (greater than) to HTML entities:

$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);

The HTML output of the code above will be (View Source):
This is some <b>bold</b> text.

The browser output of the code above will be:
This is some <b>bold</b> text.
------------------------------------------

$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes

Tip: To convert HTML entities back to characters, use the html_entity_decode() function.

Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().

PHP htmlspecialchars_decode() Function +

Convert the predefined HTML entities "<" (less than) and ">" (greater than) to characters:

PHP trim() Function +

The trim() function removes whitespace and other predefined characters from both sides of a string.

Related functions:

ltrim() - Removes whitespace or other predefined characters from the left side of a string

rtrim() - Removes whitespace or other predefined characters from the right side of a string

Syntax:

trim(string,charlist)

$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");

The output will be:
Hello World!
llo Worl

+

+

+

+

PHP md5() Function +

The md5() function calculates the MD5 hash of a string.

The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm.

From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA."

To calculate the MD5 hash of a file, use the md5_file() function.

$str = "Hello";
echo md5($str);

if (md5($str) == "8b1a9953c4611296a827abf8c47804d7")
   {
   echo "<br>Hello world!";
   exit;
   }

PHP md5_file() Function +

Calculate the MD5 hash of the text file "test.txt":

$filename = "test.txt";
$md5file = md5_file($filename);
echo $md5file;

The output will be:
d41d8cd98f00b204e9800998ecf8427e

PHP number_format() Function +

Definition and Usage:

The number_format() function formats a number with grouped thousands.

Note: This function supports one, two, or four parameters (not three).

 
echo number_format("1000000")."<br>";
echo number_format("1000000",2)."<br>";
echo number_format("1000000",2,",",".");

The output will be:
1,000,000
1,000,000.00
1.000.000,00
--------------------------------------------
$num = 1999.9;
$formattedNum = number_format($num);
echo $formattedNum."<br>";
$formattedNum = number_format($num, 2);
echo $formattedNum;

The output will be:
2,000
1,999.90

PHP str_replace() Function+

Definition and Usage:

The str_replace() function replaces some characters with some other characters in a string.

This function works by the following rules:

If the string to be searched is an array, it returns an array

If the string to be searched is an array, find and replace is performed with every array element

If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace

If find is an array and replace is a string, the replace string will be used for every find value

Note: This function is binary-safe.

Syntax

str_replace(find,replace,string,count)

Replace the characters "world" in the string "Hello world!" with "Peter":

echo str_replace("world","Peter","Hello world!");

The output will be:
Hello Peter!
------------------------------------
$arr = array("blue","red","green","yellow");

$str =str_replace("red","pink",$arr,$i);
echo "<br>" . "Replacements: $i";

foreach ($strr as $value) {
    echo "Value: $value<br />";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.

PHP str_split() Function+

Definition and Usage:

The str_split() function splits a string into an array.

Syntax

str_split(string,length)

$arr = str_split("Hello");

foreach ($arr as $value )
 echo "Value: ".$value."<br>";

Note: The default lenght is 1. If length is less than 1, the str_split() function will return FALSE. If length is larger than the length of string, the entire string will be returned as the only element of the array.

PHP stripos() Function+

Definition and Usage:

The stripos() function finds the position of the first occurrence of a string inside another string.

Note: The stripos() function is case-insensitive.

Note: This function is binary-safe.

Syntax:

stripos(string,find,start)


Find the position of the first occurrence of "php" inside the string:

echo stripos("I love php, I love php too!","PHP");

The output will be:
7

Related functions:

strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)

strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)

strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)

PHP strlen() Function+

echo strlen("Hello");

The output will be:
5

Note: Returns the length of a string on success, and 0 if the string is empty

PHP substr() Function+

Definition and Usage:

The substr() function returns a part of a string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Syntax:

substr(string,start,length)

// Positive numbers:
echo substr("Hello world",10)."<br>";
echo substr("Hello world",1)."<br>";
echo substr("Hello world",3)."<br>";
echo substr("Hello world",7)."<br>";
echo "<br>";

// Negative numbers:
echo substr("Hello world",-1)."<br>";
echo substr("Hello world",-10)."<br>";
echo substr("Hello world",-8)."<br>";
echo substr("Hello world",-4)."<br>";

The output will be:
d
ello world
lo world
orld

d
ello world
lo world
orld

The substr_count() function counts the number of times a substring occurs in a string.

Note: The substring is case-sensitive.

Note: This function does not count overlapped substrings

Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see example 3).

Syntax:

substr_count(string,substring,start,length)

PHP strtoupper() Function+

The strtoupper() function converts a string to uppercase.

Note: This function is binary-safe.

echo strtoupper("Hello WORLD!");

The output will be:
HELLO WORLD!

Related functions:

strtolower() - converts a string to lowercase
lcfirst() - converts the first character of 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