String functions


There is a big list of string functions in PHP, but let's start from the most often used of them. We've seen some of them before in the “10 useful PHP functions” lesson. Here is some new stuff:

1. str_replace

Replaces a substring with a given replacement. Works with both strings and arrays:

echo str_replace('Jennifer', 'Sally', 'Hello, Jennifer! It is me, Sam!');


Hello, Sally! It is me, Sam!

2. strcmp

Performs lexicographical compare of the given strings. Returns negative number if the first string less than the second, positive number if the first string is greater than the second, and zero otherwise. Unlike compare operators == and != it gives you lexicographical (alphabetical) order of the given strings:

$a = strcmp('Sam', 'Jennifer'); // $a > 0
$b = strcmp('Jennifer', 'Sam'); // $a < 0
$c = strcmp('Jennifer', 'Jennifer'); // $a == 0

3. strtolower and strtoupper

Transforms a given string into lowercase (strtolower) or uppercase (strtoupper);

echo strtolower('This text is lowercased<br />');
echo strtoupper('This one is uppercased');


this text is lowercased

4. lcfirst and ucfirst

These functions work like strtolower and strtoupper but affect just the first character of the given string:

echo lcfirst('LCFIRST WORKS LIKE THIS<br />');
echo ucfirst('ucfirst works like this');


ucfirst works like this

5. trim, ltrim and rtrim

These functions strip whitespaces from the beginning of the string (ltrim), end of the string (rtrim), or both (trim):

$left  = ltrim('  Hello! '); // $left  == 'Hello! '
$right = rtrim('  Hello! '); // $right == '  Hello!'
$both  = trim('  Hello! ');  // $both  == 'Hello!'

6. substr

Returns the part of the given string. The first parameter is a string itself, the second is starting position, the third is length. If the length is omitted then the rest of the string is returned:

$full_name = 'Jennifer Lockwood';
$first_name = substr($full_name, 0, 8); // $first_name == 'Jennifer'
$last_name = substr($full_name, 9); // $last_name == 'Jennifer'

7. strpos

Gives the position of the substring in the given string. If the given substring wasn't found then false is returned:

$string = 'Jennifer Lockwood';
$substring = 'Lockwood';
$position = strpos($string, $substring);

if($position === false)
    // Substring not found
    // Substring is found at $position

8. nl2br

This function replaces newline characters with <br /> HTML elements:

$text = "First line\nSecond line\nThird line";
echo nl2br($text); // First line<br />Second line<br />Third line
Rate this post:
Lesson 17
Share this page:

Learning plan

15. stdClass
The very basics of stdClass PHP class
16. JSON
How to work with JSON in PHP
17. YAML
How to work with YAML in PHP
18. String functions
Some additional functions you should learn to work with PHP strings