PHP String Manipulation

Master PHP string functions with practical examples for counting, reversing, searching, and replacing text.

📏 1. Get the Length of a String

The strlen() function returns the length of a string in bytes. It is commonly used to validate string constraints.

<?php
// Output: 12
echo strlen("Hello world!");
?>

📝 2. Count Words in a String

The str_word_count() function counts the number of words inside a string.

<?php
// Output: 2
echo str_word_count("Hello world!");
?>

🔁 3. Reverse a String

The strrev() function reverses the sequence of a string.

<?php
// Output: !dlrow olleH
echo strrev("Hello world!");
?>

🔍 4. Search for Text within a String

The strpos() function searches for a specific text within a string and returns the first occurrence's index (0-based).

<?php
// Output: 6
echo strpos("Hello world!", "world");
?>

✏️ 5. Replace Text within a String

The str_replace() function replaces specific characters or words with others within a string.

<?php
// Output: Hello Dolly!
echo str_replace("world", "Dolly", "Hello world!");
?>