PHP Strings Function


PHP includes built-in string functions which enable developers to manipulate and analyze text data efficiently. These functions enable tasks such as measuring string length via strlen(), replacing text content with str_replace(), and formatting strings through sprintf().

 

 

These functions serve critical roles in validation processes as well as parsing input and content display preparation. PHP provides numerous string functions including strpos(), substr(), and trim() that simplify different string manipulation tasks.

 


Function Description Example Code Output / Result
strlen() Returns the length of a string strlen("Hello") 5
strtoupper() Converts a string to uppercase strtoupper("hello") HELLO
strtolower() Converts a string to lowercase strtolower("HELLO") hello
ucfirst() Uppercases first character ucfirst("hello") Hello
lcfirst() Lowercases first character lcfirst("Hello") hello
ucwords() Capitalizes the first letter of each word ucwords("hello world") Hello World
strrev() Reverses a string strrev("PHP") PHP
strpos() Finds position of first occurrence of substring strpos("Hello World", "World") 6
stripos() Case-insensitive version of strpos() stripos("Hello World", "world") 6
str_replace() Replaces all occurrences of a substring str_replace("cat", "dog", "catfish") dogfish
substr() Extracts part of a string substr("abcdef", 1, 3) bcd
trim() Removes whitespace from both ends trim(" hello ") hello
ltrim() Removes whitespace from the left ltrim(" hello") hello
rtrim() Removes whitespace from the right rtrim("hello ") hello
explode() Splits a string into an array explode(",", "a,b,c") ["a", "b", "c"]
implode() Joins array elements into a string implode("-", ["a", "b", "c"]) "a-b-c"
str_repeat() Repeats a string multiple times str_repeat("Ha", 3) HaHaHa
strcmp() Compares two strings (case-sensitive) strcmp("a", "A") > 0 (since "a" > "A")
str_ireplace() Case-insensitive replace str_ireplace("HELLO", "Hi", "hello") Hi
number_format() Formats a number with grouped thousands number_format(1234567) 1,234,567

Example

 <?php
$name = "  alice cooper  ";
$cleanName = ucwords(trim($name));
echo "Cleaned Name: $cleanName<br>";

$sentence = "PHP is amazing!";
echo "Uppercase: " . strtoupper($sentence) . "<br>";
echo "Reversed: " . strrev($sentence) . "<br>";

$words = explode(" ", $sentence);
print_r($words);

$joined = implode("-", $words);
echo "<br>Joined: $joined";
?>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.