The strlen() function returns the length of a string.
$str = "Hello, world!";
echo strlen($str); // Outputs 13
The str_replace() function replaces specified characters or strings within a string.
$str = "Hello, world!";
echo str_replace("world", "PHP", $str); // Outputs Hello, PHP!
The strtolower() function converts a string to lowercase.
$str = "Hello, WORLD!";
echo strtolower($str); // Outputs hello, world!
The strtoupper() function converts a string to uppercase.
$str = "Hello, world!";
echo strtoupper($str); // Outputs HELLO, WORLD!
The substr() function returns part of a string.
$str = "Hello, world!";
echo substr($str, 0, 5); // Outputs Hello
The trim() function removes whitespace or other predefined characters from both ends of a string.
$str = " Hello, world! ";
echo trim($str); // Outputs Hello, world!
The explode() function splits a string into an array.
$str = "Hello,world!";
$arr = explode(",", $str);
print_r($arr); // Outputs Array ( [0] => Hello [1] => world! )
The implode() function joins array elements into a string.
$arr = array("Hello", "world!");
$str = implode(",", $arr);
echo $str; // Outputs Hello,world!
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'.";
}
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!
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.