Current Location: Home> Latest Articles> Comprehensive Guide to PHP String Functions: Common Techniques and Examples

Comprehensive Guide to PHP String Functions: Common Techniques and Examples

gitbox 2025-08-07

strlen() Function

The strlen() function returns the length of a string.


$str = "Hello, world!";
echo strlen($str); // Outputs 13

str_replace() Function

The str_replace() function replaces specified characters or strings within a string.


$str = "Hello, world!";
echo str_replace("world", "PHP", $str); // Outputs Hello, PHP!

strtolower() Function

The strtolower() function converts a string to lowercase.


$str = "Hello, WORLD!";
echo strtolower($str); // Outputs hello, world!

strtoupper() Function

The strtoupper() function converts a string to uppercase.


$str = "Hello, world!";
echo strtoupper($str); // Outputs HELLO, WORLD!

substr() Function

The substr() function returns part of a string.


$str = "Hello, world!";
echo substr($str, 0, 5); // Outputs Hello

trim() Function

The trim() function removes whitespace or other predefined characters from both ends of a string.


$str = "   Hello, world!   ";
echo trim($str); // Outputs Hello, world!

explode() Function

The explode() function splits a string into an array.


$str = "Hello,world!";
$arr = explode(",", $str);
print_r($arr); // Outputs Array ( [0] => Hello [1] => world! )

implode() Function

The implode() function joins array elements into a string.


$arr = array("Hello", "world!");
$str = implode(",", $arr);
echo $str; // Outputs Hello,world!

preg_match() Function

The preg_match() function performs a regex match.


$str = "Hello, world!";
if (preg_match("/world/", $str)) {
    echo "The string contains 'world'!";
} else {
    echo "The string does not contain 'world'.";
}

htmlspecialchars() Function

The htmlspecialchars() function converts special characters to HTML entities to prevent them from being interpreted as code by browsers.


$str = "Hello, world!";
echo htmlspecialchars($str); // Outputs Hello, world!

Summary

This article introduces the most commonly used PHP string functions, including length calculation, content replacement, case conversion, substring extraction, trimming, string-array conversion, regex matching, and HTML entity encoding. Mastering these functions enables developers to handle string-related tasks more flexibly and efficiently, improving code quality and development speed.