10 PHP string functions

Here are 10 useful PHP string functions.

$string = "Hello World";

1, 2, 3: trim() along with ltrim() and rtrim() strip characters from a string. trim($string) without any further arguments will strip all spaces, carriage returns, new lines, null characters, and vertical tabs from $string.

echo trim($string, 'ld');

returns “Hello Wor” because trim() only trims the edges of a string. ltrim() trims from the left only, rtrim() from the right only, and trim() from both edges.

4: str_replace() replaces all instances of a given character with another. To strip out all ‘l’s from our string, use

echo str_replace('l', '', $string);

This returns “Heo Word”.

5, 6: strtolower() transforms a string into all lower-case letters.

echo strtolower($string);

returns “hello world”. strtoupper() makes everything upper case – “HELLO WORLD”.

7: strlen() returns the length of a string.

echo strlen($string);

returns “11”. This can be a useful way to check if you have the right string.

8: substr() returns a portion of the string. It helps to know the length of the string, because

echo substr($string, 3);

will start at the 4th character (or after the 3rd, if that’s easier for you) in the string and continue to the end, returning “lo World”.

echo substr($string, 10);

will return “d”. One can use negative numbers:

echo substr($string, -1);

will also return “d”. Here substr() starts at the end of the string and returns one character.

echo substr($string, -3);

return “rld”. You can also specify a length for substr() to return.

echo substr($string, 0, 3);

returns “Hel”. It starts at position 0, and returns 3 characters. Lengths can be negative. Though with a negative length, the beginning point is the end of the word.

echo substr($string, 0, -3);

returns “Hello Wo”.

echo substr($string, 1, -3);

removes the first character (i.e. it starts after the first character, and removes the last three characters, returning “ello Wo”.

9, 10: strpos() finds the first position of a character in a string.

echo strpos($string, 'l');

returns “2”. “H” is position 0, “e” is position 1, and “l” is position 2 (and 3, and 9). strpos() is case-sensitive. stripos() is the equivalent case-insensitive function.