PHP Common String Function and Use

In This tutorial I will tell you some useful function of PHP for string.PHP is very rich language based on functions. It has many function for string manipulation, in this tutorial we will what are the common string function and how to use in PHP.

Checkout other tutorial of PHP,

strpos — Find the position of the first occurrence of a substring in a string
$mystring = 'phpflow.com';
$findme   = 'p';
$pos = strpos($mystring, $findme);
//Result is 0;

stripos — Find the position of the first occurrence of a case-insensitive substring in a string.
$mystring = 'phpflow.com';
$findme   = 'P';
$pos = stripos($mystring, $findme);
//Result is 0;
trim — Strip whitespace (or other characters) from the beginning and end of a string.
$mystring = ' abc ';
$res = trim($mystring);
//Result is abc;
ucwords — Uppercase the first character of each word in a string.
$mystring = 'hi i am parvez';
$res = ucwords($mystring);
//Result is 'Hi I Am Parvez';
ucfirst — Make a string’s first character uppercase.
$mystring = 'hi i am parvez';
$res = ucwords($mystring);
//Result is 'Hi i am parvez';
strstr — Find the first occurrence of a string.
$email  = 'test@example.com';
$domain = strstr($email, '@');
echo $domain; 
// Result is prints @example.com
stristr — Case-insensitive strstr().
$email  = 'test@Example.com';
$domain = strstr($email, 'e');
echo $domain; 
//Result is prints Example.com
strlen — Get string length.
$mystring = strlen('phpflow.com');
//Result is length 10

str_replace — Replace all occurrences of the search string with the replacement string


$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//Result is Hll Wrld f PHP
strtolower — Make a string lowercase.
$mystring = 'PhpFlow.com';
$res = strtolower($mystring);
//Result is 'phpflow.com';
strtoupper — Make a string uppercase.
$mystring = 'PhpFlow.com';
$res = strtolower($mystring);
//Result is 'PHPFLOW.COM';
strip_tags — Strip HTML and PHP tags from a string.
$text = '

Test paragraph.

%MINIFYHTML873c901b1b85931488c834cb1c801c888%%MINIFYHTML873c901b1b85931488c834cb1c801c889%
phpflow'; echo strip_tags($text); //Result is 'Test paragraph.phpflow';
sprintf — Return a formatted string.
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
//result is "There are 5 monkeys in the tree"
htmlentities — Convert all applicable characters to HTML entities.
$str = "A 'quote' is bold";

echo htmlentities($str);
// Reult is : A 'quote' is <b>bold</b>
htmlspecialchars_decode — Convert special HTML entities back to characters.
$str = "

this -> "

n"; echo htmlspecialchars_decode($str); // note that here the quotes aren't converted echo htmlspecialchars_decode($str, ENT_NOQUOTES);