Codeskill

Learn to code, step by step

Working with Strings in PHP: Manipulation and Functions

Creating them, joining them, and the functions you’ll use most often.

Understanding strings in PHP

A string is a sequence of characters. In PHP each character is one byte, so the language works with a 256-character set rather than full native Unicode.

Creating strings

Wrap text in single quotes (') or double quotes ("):

<?php
$singleQuoted = 'Hello, PHP!';
$doubleQuoted = "Hello, PHP!";
?>

Concatenating strings

Concatenation means joining strings together. In PHP you use the dot (.) operator:

<?php
$firstPart = "Hello, ";
$secondPart = "world!";
$combinedString = $firstPart . $secondPart;
echo $combinedString; // Outputs 'Hello, world!'
?>

Single vs double quotes

It matters which quotes you pick. Double-quoted strings expand variables and some escape sequences. Single-quoted strings treat almost everything literally.

<?php
$name = "Alice";
echo "Hello, $name!"; // Outputs 'Hello, Alice!'
echo 'Hello, $name!'; // Outputs 'Hello, $name!'
?>

Common string functions

PHP ships with plenty of string helpers. These come up often:

strlen()

Returns the length of a string.

<?php
echo strlen("Hello, PHP!"); // Outputs 11
?>

str_word_count()

Counts the words in a string.

<?php
echo str_word_count("Hello, world!"); // Outputs 2
?>

strrev()

Reverses a string.

<?php
echo strrev("Hello, PHP!"); // Outputs '!PHP ,olleH'
?>

strpos()

Finds the position of the first occurrence of a substring.

<?php
echo strpos("Hello, world!", "world"); // Outputs 7
?>

str_replace()

Replaces one substring with another.

<?php
echo str_replace("world", "PHP", "Hello, world!"); // Outputs 'Hello, PHP!'
?>

String formatting

When you need tidy, predictable output, these two are useful:

sprintf()

Formats a string to a specific layout.

<?php
$number = 9;
$formattedString = sprintf("The number is %02d", $number);
echo $formattedString; // Outputs 'The number is 09'
?>

number_format()

Formats a number with grouped thousands.

<?php
echo number_format("1000000"); // Outputs '1,000,000'
?>

Working with substrings

Sometimes you only need part of a string. PHP has a few functions for that:

substr()

Returns part of a string.

<?php
echo substr("Hello, world!", 7, 5); // Outputs 'world'
?>

strstr()

Finds the first occurrence of a string inside another string.

<?php
echo strstr("hello@example.com", "@"); // Outputs '@example.com'
?>

Practical example: email extraction

Split an email address into username and domain:

<?php
$email = "user@example.com";
$domain = strstr($email, '@');
$username = strstr($email, '@', true);

echo "Domain: $domain<br>";
echo "Username: $username<br>";
?>

Most PHP pages spend a fair bit of time shuffling strings around – output, form data, database values. These functions cover the everyday cases.

PreviousArrays in PHP: Organizing Data Efficiently