String manipulation in PHP involves various operations to modify, extract, and manipulate strings. PHP provides a rich set of functions and methods for working with strings. Here are some common string manipulation tasks in PHP:
- Concatenation: You can combine strings using the concatenation operator . or by using the concat() function.
phpCopy code
$str1 = “Hello, “; $str2 = “World!”; $result = $str1 . $str2; // “Hello, World!”
- String Length: To find the length of a string, use the strlen() function.
phpCopy code
$str = “Hello, World!”; $length = strlen($str); // 13
- Substring Extraction: To extract a substring from a string, use substr().
phpCopy code
$str = “Hello, World!”; $substring = substr($str, 0, 5); // “Hello”
- String Replacement: To replace one part of a string with another, use str_replace().
phpCopy code
$str = “Hello, World!”; $newStr = str_replace(“World”, “PHP”, $str); // “Hello, PHP!”
- String Splitting: To split a string into an array of substrings based on a delimiter, use explode().
phpCopy code
$str = “apple,banana,cherry”; $fruits = explode(“,”, $str); // [“apple”, “banana”, “cherry”]
- Case Conversion: You can change the case of a string using functions like strtolower(), strtoupper(), ucfirst(), and ucwords().
phpCopy code
$str = “Hello, World!”; $lower = strtolower($str); // “hello, world!” $upper = strtoupper($str); // “HELLO, WORLD!” $ucfirst = ucfirst($str); // “Hello, World!” $ucwords = ucwords($str); // “Hello, World!”
- Trimming: To remove leading and trailing whitespace or specific characters from a string, use trim(), ltrim(), or rtrim().
phpCopy code
$str = ” Hello, World! “; $trimmed = trim($str); // “Hello, World!”
- Checking Substrings: To check if a string contains a specific substring, you can use strpos() or strstr().
phpCopy code
$str = “Hello, World!”; if (strpos($str, “World”) !== false) { echo “Found ‘World’ in the string.”; }
- Formatting: You can format strings using functions like sprintf() for complex formatting or number_format() for formatting numbers.
phpCopy code
$number = 12345.6789; $formatted = number_format($number, 2); // “12,345.68”
Php code for sprint()
<!DOCTYPE html>
<html>
<body>
<?php
$number = 9;
$str = “Beijing”;
$txt = sprintf(“There are %u million bicycles in %s.”,$number,$str);
echo $txt;
?>
</body>
</html>