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 = '';
$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 = '';
$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  = '';
$domain = strstr($email, '@');
echo $domain; 
// Result is prints
stristr — Case-insensitive strstr().
$email  = '';
$domain = strstr($email, 'e');
echo $domain; 
//Result is prints
strlen — Get string length.
$mystring = strlen('');
//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 = '';
$res = strtolower($mystring);
//Result is '';
strtoupper — Make a string uppercase.
$mystring = '';
$res = strtolower($mystring);
//Result is 'PHPFLOW.COM';
strip_tags — Strip HTML and PHP tags from a string.
$text = '

Test paragraph.

%MINIFYHTMLefdcd0bc25a1386d4e319ce53fa42ab56% %MINIFYHTMLefdcd0bc25a1386d4e319ce53fa42ab57%
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);