8. PHP Strings

What you will learn

  • How to measure, search, and change strings
  • The most useful string functions
  • How to format text safely
  • Why multibyte text needs special functions

Strings in PHP

A string is text in quotes. As you saw earlier, double quotes insert variables and understand escapes such as \n, and single quotes keep text literally. PHP gives you many built-in functions for strings. A function is called by name with its input in brackets.

Length and case

PHP code

<?php
$text = "Learn PHP Today";

echo strlen($text) . "<br>";
echo strtoupper($text) . "<br>";
echo strtolower($text) . "<br>";
echo ucfirst("hello world") . "<br>";
echo ucwords("hello world");

What the browser shows

15
LEARN PHP TODAY
learn php today
Hello world
Hello World

Searching

Function Returns
str_contains($text, $part) true if the part is inside
str_starts_with($text, $part) true if it begins with the part
str_ends_with($text, $part) true if it ends with the part
strpos($text, $part) Position of the first match, or false

The first three need PHP 8. Positions start at 0.

PHP code

<?php
$text = "Learn PHP Today";

var_dump(str_contains($text, "PHP"));
var_dump(str_starts_with($text, "Learn"));
var_dump(strpos($text, "PHP"));
var_dump(strpos($text, "Java"));

What you should see (inside <pre>)

bool(true)
bool(true)
int(6)
bool(false)

Be careful: strpos() can return 0 (a match at the very start), which looks false. Test it with !== false, never plain if (strpos(...)).

Extracting and replacing

PHP code

<?php
$text = "  Learn PHP Today  ";
$clean = trim($text);

echo "[" . $clean . "]<br>";
echo substr($clean, 6, 3) . "<br>";
echo str_replace("Today", "Daily", $clean) . "<br>";
echo strrev("abc") . "<br>";
echo str_repeat("-", 10);

What the browser shows

[Learn PHP Today]
PHP
Learn PHP Daily
cba
———-

  • trim() removes spaces from both ends.
  • substr($text, start, length) returns part of a string.
  • str_replace(old, new, text) replaces every match, and is case sensitive.

Splitting and joining

PHP code

<?php
$tags = "html,css,php";
$list = explode(",", $tags);

echo count($list) . " tags, second: " . $list[1] . "<br>";
echo implode(" | ", $list);

What the browser shows

3 tags, second: css
html | css | php

explode() turns a string into an array, and implode() joins an array into a string.

Formatting

PHP code

<?php
$price = 1234.5;
$name = "Sam";
$score = 7;

echo number_format($price, 2) . "<br>";
echo sprintf("%s scored %d points (%.1f%%)", $name, $score, 70) . "<br>";
echo str_pad("7", 3, "0", STR_PAD_LEFT);

What the browser shows

1,234.50
Sam scored 7 points (70.0%)
007

sprintf() builds text from a pattern: %s is a string, %d a whole number, %.1f a decimal with one place, and %% a percent sign.

Comparing strings

Use === to test equality. It is case sensitive. To ignore case, use strcasecmp(), which returns 0 when two strings match regardless of case.

PHP code

<?php
var_dump("Apple" === "apple");
var_dump(strcasecmp("Apple", "apple") === 0);

What you should see (inside <pre>)

bool(false)
bool(true)

Text in other languages

Functions such as strlen() count bytes, not characters. A letter like é or any Arabic, Urdu, or emoji character takes more than one byte, so the count can be too big. For text that may contain such characters, use the multibyte versions: mb_strlen(), mb_substr(), mb_strtoupper(). They need the mbstring extension, which most hosts enable.

PHP code

<?php
$word = "café";

echo strlen($word) . " bytes, " . mb_strlen($word, "UTF-8") . " characters";

What the browser shows

5 bytes, 4 characters

Common mistakes

  • Using if (strpos(...)) instead of !== false.
  • Using strlen() on text with accents or non-Latin letters.
  • Expecting a string function to change the original. They return a new value, so store it.
  • Forgetting that str_replace() is case sensitive.
  • Printing visitor text without htmlspecialchars().

Exercise

Given $email = " Sam@Example.com ";, clean it (trim and lower case) and print it, then say whether it contains an @ sign using str_contains().

Show solution
<?php
$email = "  Sam@Example.com  ";
$clean = strtolower(trim($email));

echo $clean . " has @: " . (str_contains($clean, "@") ? "yes" : "no");

The output is: sam@example.com has @: yes

Knowledge check

1. Which function returns the length of a string in bytes?

strlen()

2. Which function splits a string into an array?

explode()

3. Why use mb_strlen() for some text?

It counts characters correctly for text with multibyte characters.

Summary

  • PHP has many string functions: strlen, strtoupper, str_contains, substr, str_replace, explode, implode, and more.
  • They return new strings, so save the result.
  • Use the mb_ versions for non-English text, and test strpos with !== false.
Scroll to Top