ZetCode

PHP string

last modified April 16, 2025

The PHP string is a fundamental data type for working with text. Strings are sequences of characters used to store and manipulate textual data. PHP provides extensive functions for string operations and manipulation.

Basic Definitions

A string is a series of characters where each character is the same as a byte. PHP strings can be as large as up to 2GB. Strings can be created in four ways: single quotes, double quotes, heredoc syntax, and nowdoc syntax.

Single quoted strings display things literally. Double quoted strings perform variable interpolation and special character interpretation. Heredoc behaves like double quoted strings. Nowdoc behaves like single quoted strings.

PHP offers over 100 built-in string functions for common operations like searching, replacing, formatting, comparing, and modifying strings.

Basic String Creation

This example demonstrates different ways to create strings in PHP.

basic_string.php
<?php

declare(strict_types=1);

$single = 'Single quoted string';
$double = "Double quoted string with $single";
$heredoc = <<<EOT
Heredoc string (like double quotes)
Can span multiple lines
EOT;
$nowdoc = <<<'EOT'
Nowdoc string (like single quotes)
No variable interpolation
EOT;

echo $single . "\n";
echo $double . "\n";
echo $heredoc . "\n";
echo $nowdoc . "\n";

The code shows four string creation methods. Single quotes don't interpolate variables. Double quotes do. Heredoc allows multiline strings with interpolation. Nowdoc is for multiline strings without interpolation.

String Concatenation

This example shows how to combine strings using concatenation.

concatenation.php
<?php

declare(strict_types=1);

$firstName = "John";
$lastName = "Doe";

// Using concatenation operator
$fullName = $firstName . " " . $lastName;
echo $fullName . "\n";

// Using concatenation assignment
$greeting = "Hello, ";
$greeting .= $fullName;
echo $greeting . "\n";

The dot (.) operator concatenates strings. The .= operator appends to existing strings. Concatenation doesn't add spaces automatically. Multiple concatenations can be chained together in one expression.

String Length and Position

This example demonstrates finding string length and character positions.

length_position.php
<?php

declare(strict_types=1);

$text = "Hello World";

// Get string length
$length = strlen($text);
echo "Length: $length\n";

// Find character position
$pos = strpos($text, "World");
echo "'World' starts at position: $pos\n";

// Case-insensitive search
$pos = stripos($text, "world");
echo "'world' (case-insensitive) at: $pos\n";

strlen returns the byte length of a string. strpos finds the position of a substring. String positions start at 0. stripos performs case-insensitive searches. These functions return false if not found.

String Modification

This example shows common string modification functions.

modification.php
<?php

declare(strict_types=1);

$text = "   php string tutorial   ";

// Trim whitespace
$trimmed = trim($text);
echo "Trimmed: '$trimmed'\n";

// Convert case
$lower = strtolower($trimmed);
$upper = strtoupper($trimmed);
echo "Lower: $lower\n";
echo "Upper: $upper\n";

// Replace text
$replaced = str_replace("tutorial", "guide", $trimmed);
echo "Replaced: $replaced\n";

trim removes whitespace from both ends. strtolower and strtoupper change case. str_replace substitutes text. These functions return new strings rather than modifying the original.

String Splitting

This example demonstrates splitting strings into parts.

splitting.php
<?php

declare(strict_types=1);

$csv = "apple,banana,orange,grape";
$names = "John|Jane|Jim|Julie";

// Split by delimiter
$fruits = explode(",", $csv);
print_r($fruits);

// Split with limit
$limited = explode("|", $names, 2);
print_r($limited);

// Join array into string
$joined = implode(" - ", $fruits);
echo $joined . "\n";

explode splits a string by delimiter into an array. The optional limit parameter restricts the number of splits. implode joins array elements into a string. These are useful for CSV processing and similar tasks.

String Formatting

This example shows various string formatting techniques.

formatting.php
<?php

declare(strict_types=1);

$price = 19.99;
$count = 5;
$item = "widget";

// printf formatting
printf("Each %s costs \$%.2f. %d items cost \$%.2f.\n", 
    $item, $price, $count, $price * $count);

// sprintf returns formatted string
$message = sprintf("Thank you for purchasing %d %ss!", $count, $item);
echo $message . "\n";

// Number formatting
$formatted = number_format(1234567.89, 2, ".", ",");
echo "Formatted number: $formatted\n";

printf outputs formatted strings. sprintf returns formatted strings. Format specifiers like %s (string), %d (integer), and %f (float) control formatting. number_format formats numbers with thousands separators.

Multibyte String Functions

This example demonstrates working with multibyte (UTF-8) strings.

multibyte.php
<?php

declare(strict_types=1);

$text = "こんにちは世界"; // Japanese "Hello World"

// Multibyte string length
$length = mb_strlen($text);
echo "Length in characters: $length\n";

// Multibyte substring
$sub = mb_substr($text, 0, 5);
echo "First 5 characters: $sub\n";

// Multibyte case conversion
$upper = mb_strtoupper("café");
echo "Uppercase: $upper\n";

// Check encoding
$encoding = mb_detect_encoding($text);
echo "Detected encoding: $encoding\n";

Multibyte functions handle UTF-8 and other encodings properly. mb_strlen counts characters, not bytes. mb_substr works with character positions. Always use mb_ functions for multilingual applications to avoid encoding issues.

Best Practices

Source

PHP string Documentation

This tutorial covered PHP strings with practical examples showing creation, manipulation, formatting, and multibyte handling of string data.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all PHP basics tutorials.