In this lesson, you will learn about String Functions in PHP, their usage, and examples to better understand the topic.
Here we will examine a few frequently used functions for manipulating strings.
strlen()
str_word_count()
strrev()
strpos()
str_replace()
The PHP method returns the length of a String with strlen()
$stringVar1="This is PHP Tutorial"; echo strlen($stringVar1);
Output
20
This PHP method counts the words in a string
$stringVar1="This is PHP Tutorial"; echo str_word_count($stringVar1);
Output
4
A string is reversed using the PHP strrev()
function.
$stringVar1="This is PHP Tutorial"; echo strrev($stringVar1);
Output
lairotuT PHP si sihT
The PHP strpos()
method looks for a particular text within a string. The function returns the first match’s character position if a match is discovered. It will return FALSE if no match is found.
$stringVar1="This is PHP Tutorial"; echo strpos($stringVar1,"is");
Output
is 2
The PHP str replace()
function swaps some characters in a string for other characters.
$stringVar1="This is PHP Tutorial"; echo str_replace("Tutorial", "Lesson", "PHP Tutorial!");
Output
PHP Lesson!.
<!DOCTYPE html> <html> <body> <?php $stringVar1 = "This is PHP Tutorial"; echo strlen($stringVar1) . "<br>"; echo str_word_count($stringVar1) . "<br>"; echo strrev($stringVar1) . "<br>"; echo strpos($stringVar1, "is") . "<br>"; echo str_replace("Tutorial", "Lesson", "PHP Tutorial!"); // outputs PHP Lesson! ?> </body> </html>
Output
20 4 lairotuT PHP si sihT 2 PHP Lesson!
This concludes the PHP String Functions lesson. In the next class, you will learn about PHP Forms and their usage.