➤ In this note we will look at some commonly used functions to manipulate strings.
•
strlen()
// function returns the length of a string.
echo strlen("Hello"); // outputs 5
•
str_word_count()
// function counts the number of words in a string.
echo str_word_count("Hello world!"); // outputs 2
•
strrev()
// function reverses a string.
echo strrev("Levani"); // outputs inaveL
•
strpos()
/* function searches for a specific text within a string.
If a match is found, the function returns the character position of
the first match. If no match is found, it will return FALSE.*/
echo strpos("Hello world!", "l"); // outputs 2
// why ? index 0 = "H", index 1 = "e" and index 2 = "l"
•
str_replace()
// function replaces some characters with some other characters in a string.
echo str_replace("l", "L", "levani"); // outputs Levani
•
substr()
// function return part of a string between given indexes
echo substr("Hello world", 6)."\n"; // outputs world
echo substr("Hello world", 9, 2)."\n"; // outputs ld
echo substr("abcdef", -1)."\n"; // outputs f
echo substr("abcdef", -2)."\n"; // outputs ef
echo substr("abcdef", -3, 1)."\n"; // outputs d
•
strtoupper()
// function make a string uppercase
echo strtoupper("i love coding")."\n"; // outputs I LOVE CODING
•
strtolower()
// function make a string lowercase
echo strtolower("PHP")."\n"; // outputs php
•
explode()
// function Split a string by a string
echo var_dump(explode(" ", "I am 19 years old"))."\n"; // outputs "I" "am" "19" ...
•
implode()
// function join array elements with a string
echo implode(" ", ['Nika', 'Giorgi',"Saba"]); // outputs Nika Giorgi Saba
•
trim()
// function strip whitespace (or other characters) from the beginning and end of a string
echo trim(" How are you ? ")."\n";
// outputs How are you ? (without any whitespace before and after the text)