Strings are a sequence of characters, and PHP provides a massive library of built-in functions to manipulate them. From finding sub-strings to replacing text, these functions are essential for handling any user input or data processing.
strlen()The strlen() function returns the length of a string (the number of
characters).
<?php
echo strlen("Hello World!"); // Output: 12
?>
str_word_count()The str_word_count() function counts the number of words in a string.
<?php
echo str_word_count("Hello World!"); // Output: 2
?>
strrev()The strrev() function reverses a string.
<?php
echo strrev("Hello World!"); // Output: !dlroW olleH
?>
strpos()The strpos() function searches for a specific text within a string. If a
match is found, it returns the character position of the first match.
If no match is found, it returns FALSE.
<?php
echo strpos("Hello World!", "World"); // Output: 6
?>
str_replace()The str_replace() function replaces some characters with some other
characters in a string.
<?php
echo str_replace("World", "PHP", "Hello World!"); // Output: Hello PHP!
?>
strpos(), the
first position is 0, not 1. Keep this in mind when searching for the very first word in
a string.
str_ireplace() or stripos().
| Function | Description |
|---|---|
strlen() |
Returns the length of a string. |
strpos() |
Finds the position of the first occurrence. |
str_replace() |
Replaces all occurrences of a search string. |
strtoupper() |
Converts a string to uppercase. |
strtolower() |
Converts a string to lowercase. |
trim() |
Removes whitespace from both sides. |