PHP - PHP String Manipulation and Multibyte Strings

String manipulation is an important part of PHP programming because applications frequently need to work with text. Usernames, names, addresses, emails, messages, search terms, file contents, HTML content, and database values are all commonly represented as strings.

PHP provides many built-in functions for creating, searching, modifying, splitting, comparing, and formatting strings. PHP also provides the mbstring extension for working correctly with multibyte character encodings such as UTF-8.

1. What Is a String in PHP?

A string is a sequence of characters enclosed within single quotes or double quotes.

$name = "Rahul";
$message = 'Welcome to PHP';

Both single-quoted and double-quoted strings are supported, but they behave differently when variables and escape sequences are used.

$name = "Rahul";

echo "Hello $name";
echo 'Hello $name';

The first statement displays:

Hello Rahul

The second statement displays:

Hello $name

Double-quoted strings allow variable interpolation, while single-quoted strings generally treat the contents literally.

2. Finding the Length of a String

The strlen() function returns the number of bytes in a string.

$text = "Hello";

echo strlen($text);

Output:

5

This works as expected for ordinary English text because each character normally occupies one byte in ASCII-compatible encoding.

However, strlen() should not be assumed to return the number of visible characters for UTF-8 text.

For example:

$text = "Café";

echo strlen($text);

Depending on the encoding, accented or non-ASCII characters may occupy multiple bytes.

This distinction becomes especially important when applications work with Indian languages, Chinese, Japanese, Arabic, or other Unicode text.

3. Extracting Part of a String

The substr() function extracts part of a string.

$text = "Programming";

echo substr($text, 0, 7);

Output:

Program

The first argument is the original string, the second is the starting position, and the third specifies the number of characters or bytes to extract according to the function's byte-oriented behavior.

Negative positions can also be used.

$text = "Programming";

echo substr($text, -3);

Output:

ing

This is useful when extracting file extensions, codes, prefixes, suffixes, or portions of text.

4. Replacing Text

The str_replace() function replaces one piece of text with another.

$text = "I like Java";

$result = str_replace("Java", "PHP", $text);

echo $result;

Output:

I like PHP

Multiple replacements can also be performed.

$text = "PHP is difficult";

$text = str_replace("difficult", "powerful", $text);

echo $text;

Output:

PHP is powerful

The function is commonly used for cleaning text, replacing placeholders, modifying templates, and processing user-generated content.

5. Searching for Text

PHP provides several functions for locating text inside another string.

The strpos() function finds the position of the first occurrence of a substring.

$text = "Learn PHP programming";

$position = strpos($text, "PHP");

echo $position;

The returned position is zero-based, meaning the first character has position 0.

A common mistake is checking the result incorrectly:

if (strpos($text, "Learn")) {
    echo "Found";
}

This can fail when the searched text occurs at position 0, because 0 is considered false in a Boolean context.

The safer approach is:

if (strpos($text, "Learn") !== false) {
    echo "Found";
}

The strict comparison is important because strpos() returns false when the text is not found.

6. Converting Text to Lowercase and Uppercase

PHP provides functions for changing letter case.

$text = "Hello PHP";

echo strtolower($text);

Output:

hello php

Similarly:

$text = "hello php";

echo strtoupper($text);

Output:

HELLO PHP

For Unicode text, ordinary strtolower() and strtoupper() may not correctly handle all characters. The mbstring extension provides multibyte-aware alternatives.

$text = "Example";

echo mb_strtolower($text, "UTF-8");

7. Removing Whitespace

The trim() function removes whitespace from the beginning and end of a string.

$name = "   Rahul   ";

echo trim($name);

Output:

Rahul

Related functions include:

ltrim($text);
rtrim($text);

ltrim() removes whitespace from the beginning, while rtrim() removes whitespace from the end.

This is particularly useful when processing form input.

$name = trim($_POST["name"]);

Trimming input can prevent accidental spaces from affecting comparisons and stored values.

8. Splitting a String

The explode() function divides a string into an array based on a delimiter.

$fruits = "Apple,Banana,Orange";

$result = explode(",", $fruits);

print_r($result);

The resulting array contains:

Apple
Banana
Orange

This is useful when processing comma-separated values or other delimiter-based data.

For example:

$skills = "PHP,HTML,CSS,JavaScript";

$skillList = explode(",", $skills);

foreach ($skillList as $skill) {
    echo $skill . "<br>";
}

9. Joining Array Elements

The opposite operation can be performed using implode().

$skills = ["PHP", "HTML", "CSS"];

$result = implode(", ", $skills);

echo $result;

Output:

PHP, HTML, CSS

This is useful when converting arrays into readable strings, generating CSV-like output, or constructing lists.

10. Comparing Strings

PHP provides several ways to compare strings.

The strcmp() function compares two strings.

$result = strcmp("PHP", "PHP");

echo $result;

When the strings are equal, the result is 0.

For equality checks, the strict comparison operator is often appropriate:

if ($username === "admin") {
    echo "Administrator";
}

Using === checks both the value and the type, which helps avoid unexpected type conversions.

11. Removing or Replacing Portions of Text

Functions such as str_replace() can be used to remove text by replacing it with an empty string.

$text = "PHP programming language";

$text = str_replace("programming ", "", $text);

echo $text;

Output:

PHP language

Multiple replacement values can also be supplied.

$text = "PHP, HTML, CSS";

$text = str_replace(
    [",", " "],
    [";", ""],
    $text
);

echo $text;

This technique is useful when transforming structured text.

12. Repeating Strings

The str_repeat() function repeats a string a specified number of times.

echo str_repeat("-", 20);

Output:

--------------------

It can be useful for generating separators, formatting output, or creating repeated text.

13. Reversing a String

The strrev() function reverses a string.

$text = "PHP";

echo strrev($text);

Output:

PHP

For a different example:

$text = "Hello";

echo strrev($text);

Output:

olleH

Care should be taken with multibyte text because strrev() is not designed to understand Unicode characters as human-readable characters.

14. Multibyte Strings

A major limitation of many traditional PHP string functions is that they operate on bytes rather than Unicode characters.

UTF-8 is a variable-width encoding. Some characters occupy one byte, while others occupy multiple bytes.

For example, consider:

$text = "こんにちは";

Using ordinary byte-oriented functions can produce unexpected results when the intention is to count or manipulate visible characters.

PHP's mbstring extension addresses this problem.

The extension provides functions such as:

mb_strlen()
mb_substr()
mb_strtolower()
mb_strtoupper()
mb_strpos()

For example:

$text = "こんにちは";

echo mb_strlen($text, "UTF-8");

This counts the Unicode characters rather than simply counting their encoded bytes.

15. mb_strlen() Versus strlen()

Consider:

$text = "こんにちは";

echo strlen($text);

strlen() measures the number of bytes.

Now consider:

echo mb_strlen($text, "UTF-8");

mb_strlen() understands the multibyte encoding and counts the characters appropriately.

Therefore, when working with UTF-8 text, mb_strlen() is generally more appropriate when the requirement is to determine the number of characters.

16. Multibyte Substrings

The same principle applies when extracting text.

For ordinary ASCII text:

$text = "Programming";

echo substr($text, 0, 5);

For Unicode text, mb_substr() is preferable:

$text = "こんにちは";

echo mb_substr($text, 0, 3, "UTF-8");

This allows PHP to treat the input as UTF-8 text rather than simply cutting a sequence of bytes.

17. Multibyte Case Conversion

Case conversion is another area where Unicode awareness matters.

$text = "HELLO";

echo mb_strtolower($text, "UTF-8");

Output:

hello

For Unicode languages that have case distinctions, mbstring provides more appropriate handling than basic byte-oriented functions.

18. Checking Whether a String Starts or Ends With Specific Text

Modern PHP provides str_starts_with() and str_ends_with().

For example:

$url = "https://example.com";

if (str_starts_with($url, "https://")) {
    echo "Secure URL";
}

Similarly:

$file = "report.pdf";

if (str_ends_with($file, ".pdf")) {
    echo "PDF file";
}

These functions make common string checks easier to understand than manually using position-based functions.

19. String Interpolation

PHP allows variables to be inserted directly into double-quoted strings.

$name = "Anita";
$age = 25;

echo "My name is $name and I am $age years old.";

Output:

My name is Anita and I am 25 years old.

Curly braces can be used when variable boundaries need to be made clear.

$name = "Anita";

echo "Welcome, {$name}!";

This is particularly useful when a variable is immediately followed by other characters.

20. Practical Example

The following example demonstrates several string manipulation operations together:

$name = "   Rahul Sharma   ";

$name = trim($name);

$name = strtolower($name);

$parts = explode(" ", $name);

foreach ($parts as $part) {
    echo $part . "<br>";
}

The program first removes unnecessary whitespace, converts the text to lowercase, separates the name into individual parts, and then processes each part.

21. Practical Uses of String Manipulation

String manipulation is commonly used in:

  • Processing form input

  • Validating usernames and email addresses

  • Searching application data

  • Formatting names and addresses

  • Processing CSV files

  • Creating URLs and slugs

  • Parsing log files

  • Formatting API responses

  • Cleaning imported data

  • Generating reports

  • Processing multilingual content

  • Preparing text for database operations

22. Important Considerations

When working with strings in PHP, developers should remember that not every string function is Unicode-aware.

For ordinary English text, functions such as strlen(), substr(), and strtolower() may be sufficient. For multilingual UTF-8 applications, functions from the mbstring extension should generally be considered.

It is also important to distinguish between bytes and characters. A byte is a unit of encoded data, while a character represents a textual symbol. With UTF-8, one character can require multiple bytes.

Conclusion

PHP provides a comprehensive collection of functions for manipulating strings. Functions such as strlen(), substr(), strpos(), str_replace(), trim(), explode(), and implode() handle common text-processing requirements.

For modern applications that work with international and multilingual text, the mbstring extension is especially important. Functions such as mb_strlen(), mb_substr(), mb_strtolower(), and mb_strtoupper() allow developers to work with multibyte encodings such as UTF-8 more reliably.

Understanding both ordinary string functions and multibyte string handling enables PHP developers to build applications that process text correctly across different languages and character sets.