Skip to content

String Manipulation

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:

  1. 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!” 

  1. String Length: To find the length of a string, use the strlen() function.

phpCopy code

$str = “Hello, World!”; $length = strlen($str); // 13 

  1. Substring Extraction: To extract a substring from a string, use substr().

phpCopy code

$str = “Hello, World!”; $substring = substr($str, 0, 5); // “Hello” 

  1. 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!” 

  1. 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”] 

  1. 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!” 

  1. 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!” 

  1. 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.”; } 

  1. 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>