HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP String Functions

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.


1. String Length - strlen()

The strlen() function returns the length of a string (the number of characters).

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

2. Word Count - 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
?>

3. Reversing Strings - strrev()

The strrev() function reverses a string.

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

4. Search Within a String - 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
?>

5. Replace Text - 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!
?>
Indexing starts at 0: In functions like strpos(), the first position is 0, not 1. Keep this in mind when searching for the very first word in a string.
Warning: PHP string functions are case-sensitive by default. For case-insensitive operations, look for "i" counterparts like str_ireplace() or stripos().

Common String Functions

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.