Home >Backend Development >PHP Tutorial >PHP string function usage example
PHP is a very popular programming language that provides many functions for processing strings. These functions can be used for string interception, formatting, replacement, search and other operations. This article will introduce some commonly used PHP string functions and their usage examples.
strlen() function can get the string length. Its syntax is as follows:
int strlen (string $string)
$string indicates the string whose length you want to get. The following is an example of using the strlen() function:
$str = "Hello, world!";
$length = strlen($str); // Get the length of the string
echo $ length; // Output 13
The substr() function can intercept strings. Its syntax is as follows:
string substr (string $string, int $start [, int $length])
$string represents the string to be intercepted, $start represents the starting position of interception , $length represents the number of characters to be intercepted (optional parameter). The following is an example of using the substr() function:
$str = "Hello, world!";
$subStr = substr($str, 0, 5); // intercept the first 5 characters
echo $subStr; // Output Hello
str_replace() function can replace specified characters in a string. Its syntax is as follows:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
$search represents the character to be replaced, $replace represents The characters after replacement, $subject represents the string to be replaced, and $count represents the number of replacements (optional parameter). The following is an example of using the str_replace() function:
$str = "Hello, world!";
$newStr = str_replace("world", "PHP", $str); // Will Replace world in the string with PHP
echo $newStr; // Output Hello, PHP!
string strtoupper (string $string)
$newStr1 = strtolower($str); // Convert the string to Lowercase
$newStr2 = strtoupper($str); //Convert the string to uppercase
echo $newStr1; //Output hello, world!
echo $newStr2; //Output HELLO, WORLD!
" ] )
$newStr = trim($str); // Remove spaces on both sides of the string
echo $newStr; // Output Hello, world!
$arr = explode(",", $str); // Split by, String
print_r($arr); // Output Array ( [0] => apple [1] => orange [2] => banana )
The above is the detailed content of PHP string function usage example. For more information, please follow other related articles on the PHP Chinese website!