PHP String Handling

A string is a series of characters, like “Hello PHP”. Working with text is one of the most common jobs in web development, so PHP gives many functions to handle strings.


Create and join strings

You can write a string in single quotes or double quotes. In double quotes PHP replaces the variables with their values, in single quotes it does not. The dot (.) joins strings.

<?php
$name = "Robin";

echo "Hello $name<br>";
echo 'Hello $name<br>';
echo "Hello " . $name . "!";
?>

Output:

Tutorials Class - Output Window

Hello Robin
Hello $name
Hello Robin!

See the details in single vs double quote strings.


Common string functions

FunctionWhat it doesExample result
strlen($s)Length in bytes. Use mb_strlen() for non-English text. See strlen vs mb_strlenstrlen(“PHP”) = 3
strtoupper(), strtolower()Change the case“hello” to “HELLO”
ucfirst(), ucwords()Capital first letter of text or of each word“hello world” to “Hello World”
trim(), ltrim(), rtrim()Remove spaces from the ends” hi ” to “hi”
substr($s, start, length)Take a part of a stringsubstr(“Hello World”, 6, 5) = “World”
strrev($s)Reverse a string“Hello” to “olleH”
str_replace()Replace text. See replace a part of a stringstr_replace(“a”, “o”, “cat”) = “cot”
strpos()Find the position of a text. See PHP strpos()strpos(“Hello”, “l”) = 2
str_contains()Check if text exists (PHP 8). See contains a substringtrue or false
str_word_count()Count the words. See count words2
explode(), implode()Split to an array and join back. See explode() and implode()
<?php
echo strtoupper("hello") . "<br>";
echo ucwords("hello world") . "<br>";
echo substr("Hello World", 6, 5) . "<br>";
echo strrev("Hello") . "<br>";
echo "[" . trim("  hi  ") . "]<br>";
var_dump(str_starts_with("Tutorials Class", "Tut"));
?>

Output:

Tutorials Class - Output Window

HELLO
Hello World
World
olleH
[hi]
bool(true)


Format strings and numbers

<?php
echo sprintf("Price: %.2f", 99.5) . "<br>";
echo number_format(1234567.891, 2);
?>

Output:

Tutorials Class - Output Window

Price: 99.50
1,234,567.89

sprintf() puts values into a text pattern, and number_format() adds thousand separators and fixes the decimals.


Special characters and safety

  • Use a backslash to write special characters in double quotes, like \n (new line) and \" (a quote).
  • Before you print user text in a page, convert it with htmlspecialchars(). See XSS and strip_tags().
Note: Strings are counted from 0. So in “Hello” the letter H is at position 0. A negative start like substr("Hello", -3) counts from the end and gives “llo”.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a PHP program to reverse the string
Write a PHP program to find the length of the string
Write a PHP program to count the words in the string
Write a PHP program to convert a string into uppercase
PHP Array to String Conversion (favourite colours chosen by user)
Interview Questions & Answers
No Content Found.