PHP String Functions
- Previous Page PHP Data Types
- Next Page PHP Constants
A string is a sequence of characters, such as "Hello world!"
PHP String Functions
In this section, we will learn about commonly used string manipulation functions.
PHP strlen() function
The strlen() function returns the length of a string, counted by characters.
The following example returns the length of the string "Hello world!":
Example
<?php echo strlen("Hello world!"); ?>
The output of the above code is: 12
Tip:The strlen() function is commonly used in loops and other functions, and it is important to determine when a string ends. (For example, in a loop, we may need to stop the loop after the last character of the string).
Count words in a string
The PHP str_word_count() function counts words in a string:
Example
<?php echo str_word_count("Hello world!"); // Outputs 2 ?>
The output of the above code is:
2
Reverse the String
PHP strrev() Function Reverses the String:
Example
<?php echo strrev("Hello world!"); // Outputs !dlrow olleH ?>
The output of the above code is:
!dlrow olleH
PHP strpos() Function
The strpos() function is used to search for a specified character or text within a string.
If a match is found, it will return the position of the first matching character. If no match is found, it will return FALSE.
The following example retrieves the text "world" from the string "Hello world!":
Example
<?php echo strpos("Hello world!","world"); ?>
The output of the above code is: 6.
Tip:In the above example, the position of the string "world" is 6. The reason it is 6 (not 7) is that the position of the first character in the string is 0, not 1.
Replace text in the string
The PHP str_replace() function replaces some strings with other strings in a string.
The following example replaces the text "world" with "Kitty":
Example
<?php echo str_replace("world", "Kitty", "Hello world!"); // Outputs Hello Kitty! ?>
The output of the above code is:
Hello Kitty!
Complete PHP String Reference Manual
For a complete reference manual of string functions, please visit our PHP String Reference Manual.
This manual provides a brief description and examples for each function!
- Previous Page PHP Data Types
- Next Page PHP Constants