PHP provides several built-in functions to manipulate strings easily. These functions help with finding lengths, replacing text, changing case, extracting substrings, and more.
๐น Commonly Used PHP String Functions
Here are some essential PHP string functions:
strlen()
– Get the length of a string.strtolower()
/strtoupper()
– Convert string case.trim()
– Remove whitespace from both ends.substr()
– Extract part of a string.str_replace()
– Replace text in a string.strpos()
– Find the position of a substring.
๐ Example 1: Get String Length
The strlen()
function returns the number of characters in a string.
<?php $text = "Hello, World!"; echo "Length: " . strlen($text); ?>
๐ Example 2: Convert String to Lowercase & Uppercase
Use strtolower()
and strtoupper()
to change case.
<?php $text = "Hello, World!"; echo "Lowercase: " . strtolower($text) . "<br>"; echo "Uppercase: " . strtoupper($text); ?>
๐ Example 3: Trim Whitespace
The trim()
function removes extra spaces from the beginning and end of a string.
<?php $text = " Hello, World! "; echo "Without trim: '$text' <br>"; echo "With trim: '" . trim($text) . "'"; ?>
๐ Example 4: Extract a Substring
The substr()
function extracts part of a string.
<?php $text = "Hello, World!"; echo "Extracted: " . substr($text, 7, 5); ?>
Explanation: Extracts 5 characters starting from index 7, outputting World
.
๐ Example 5: Replace Text in a String
The str_replace()
function replaces words in a string.
<?php $text = "I love PHP!"; $new_text = str_replace("PHP", "coding", $text); echo $new_text; ?>
Explanation: Replaces PHP
with coding
, outputting I love coding!
.
๐ Example 6: Find Position of a Word
The strpos()
function finds the position of the first occurrence of a substring.
<?php $text = "Hello, World!"; $position = strpos($text, "World"); echo "Position of 'World': " . $position; ?>
Explanation: Finds World
at index 7
.
๐น Key Takeaways
- Use
strlen()
to find the length of a string. - Use
strtolower()
andstrtoupper()
to change case. - Use
trim()
to remove unnecessary whitespace. - Use
substr()
to extract parts of a string. - Use
str_replace()
to replace text in a string. - Use
strpos()
to locate substrings.
๐ Practice Time!
Try modifying these examples and experiment with PHP string functions
to improve your understanding! ๐