PHP Strings

PHP strings are sequences of characters used for text. PHP has a rich set of string functions, and knowing a dozen of them covers most everyday tasks such as formatting names, searching text and building messages.

Single vs Double Quotes

Double quotes interpolate variables and escape sequences like \n. Single quotes print text literally, which is a little faster and safer for plain text.

<?php
$user = "Ali";
echo "Hi $user\n";
echo 'Hi $user\n';
echo "\n";
echo "Total: {$user}'s cart";
Hi Ali
Hi $user\n
Total: Ali's cart

Concatenation

Join strings with the dot operator, and append with .=.

<?php
$msg = "Hello";
$msg .= ", ";
$msg .= "PHP";
echo $msg . "!";
Hello, PHP!

Common PHP String Functions

<?php
$s = "Learn PHP the easy way";
echo strlen($s), "\n";
echo strtoupper($s), "\n";
echo str_replace("easy", "modern", $s), "\n";
echo substr($s, 6, 3), "\n";
echo ucwords("naeem amin"), "\n";
var_dump(str_contains($s, "PHP"));
echo trim("  padded  "), "|";
22
LEARN PHP THE EASY WAY
Learn PHP the modern way
PHP
Naeem Amin
bool(true)
padded|

Splitting and Joining

explode() turns a string into an array, and implode() does the reverse.

<?php
$tags = explode(",", "php,laravel,mysql");
print_r($tags);
echo implode(" | ", $tags);
Array
(
    [0] => php
    [1] => laravel
    [2] => mysql
)
php | laravel | mysql

Heredoc and sprintf

Heredoc is great for multi-line text with variables. sprintf() formats numbers and text precisely.

<?php
$name = "Sara";
$price = 9.5;
echo <<<TXT
Dear $name,
Your order is ready.
TXT;
echo "\n" . sprintf("Price: %.2f USD", $price);
Dear Sara,
Your order is ready.
Price: 9.50 USD

Frequently asked questions

How do you concatenate strings in PHP?

Use the dot operator, for example $a . " " . $b, or append with $a .= "text". Double-quoted interpolation is another option.

How do I check if a string contains a word in PHP?

In PHP 8 use str_contains($haystack, $needle). str_starts_with() and str_ends_with() are also available.

Why do strlen results look wrong for Urdu or emoji text?

strlen counts bytes, not characters. Use mb_strlen() and other mb_ functions for multibyte UTF-8 text.