Useful php string function with practical examples

As a Open source developer (PHP), you needs to deal with different types of functions on daily basis. While working on strings, I found following basic string functions useful on most of the occasions in my projects. I listed out them with examples. Lets explore them.

1. substr() – Return part of a string
Example :

$str = 'demo#123 - testing string function';

if( "demo#123" == substr($str, 0, 8) ) {
echo 'My sub string from start -->' . substr($str, 0, 8);

if( "123" == substr($str, 5, 3) ) {
echo 'My sub string from somewhere in middle -->' . substr($str, 5, 3);

2. sprintf() – Return a formatted string
Example :

$num = 5;
$location = 'tree';
$format = 'The %s contains %d monkeys';
echo sprintf($format, $location, $num);

3. implode()/join() – Join array elements with a string
Example :

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

4. strlen() -  Get string length
Example :

$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7

Note : strlen() returns the number of bytes rather than the number of characters in a string. strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

Use mb_strlen to get encoded special character length

5. str_replace() – Replace all occurrences of the search string with the replacement string
Example :

echo str_replace("Hard", "Smart", "We love PHP, Be Hard Worker Be Happy"); // We love PHP, Be Smart Worker Be Happy

Note : If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search.

6. explode() – Split a string by string and returns array of string
Example :

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" " , $pizza); // here delimiter is single space
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

Note : explode function will through warning if an empty delimiter given

Example with limit argument

$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -2));

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
If the limit parameter is negative, all components except the last -limit are returned.
If the limit parameter is zero, then this is treated as 1.

7. strpos() – Find the position of the first occurrence of a substring in a string

Example :

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";

Note : There is third optional parameter (offset) – if specified, search will start this number of characters counted from the beginning of the string.

8. trim() – Strip whitespace (or other characters) from the beginning and end of a string

Example :

$strPunchLine = ' Be Smart Be Happy ';
echo trim($strPunchLine);

Note :
ltrim() – Strip whitespace (or other characters) from the beginning of a string
rtrim() – Strip whitespace (or other characters) from the end of a string

9. addslashes() – Returns a string with backslashes before characters that need to be quoted. These characters are single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte)

Example :

$str = "We're learning PHP string functions";
echo addslashes($str); // We\'re learning PHP string functions

10. number_format() – Format a number with grouped thousands

Example :

$number = 1234.56789;
echo number_format($number, 2); // 1,234.57

You can explore more string functions on

Thanks for reading entire post. Be Smart Be Happy!

Source :

2 Responses to Useful php string function with practical examples

  1. Balraj Parmar says:

    Nice.. It will help me to give you site to my students to lean this basic function.

  2. admin says:


    Thanks for recommending my blog.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>