Friday, September 6, 2019

PHP String Functions Part I


PHP String Functions


addslashes()
If any string contains backslashes(\), single quotes('), double quotes("), and NULL. Then this function adds backslashes(\) in front of it.

Syntax:
addslashes(string_variable)

For Example:
$str = "Ram's brother is very bad man.";
echo addslashes($str);

Answer is:
Ram\'s brother is very bad man.


stripslashes()
It is used to remove backslashes from string which is added by addslashes function.

Syntax:
stripslashes(string_variable)

For Example:
$strVal = stripslashes("Ram\'s brother is very bad man.");

Answer is:
Ram's brother is very bad man.


echo()
If we want to display anything on browser, then we use echo function. We can display one or more string with echo.

Syntax:
echo(string1, string2, ...)

For Example:
$str = "Ram's brother is very bad man.";
echo $str;

Answer is:
Ram's brother is very bad man.

explode()
If we want to break any string value into array, then we use explode function.

Syntax:
explode(separator, string_variable);

For Example,
$str = "Ram's brother is very bad man.";
$str_split = explode(" ", $str); //here single space is separator
echo "<pre>";
print_r($str_split);

Answer is:
Array
(
    [0] => Ram's
    [1] => brother
    [2] => is
    [3] => very
    [4] => bad
    [5] => man.
)


implode()
If we want to convert array values to string value, then we use implode function.

Syntax:
implode(separator, array_variable)

For Example,
$arrVar = array("Ram", "is", "a", "good", "boy");
$strVal = implode(" ", $arrVar);
echo $strVal;

Answer is:
Ram is a good boy


ltrim(): It use to remove whitespace or any predefine character from left side of string.
rtrim(): It use to remove whitespace or any predefine character from right side of string.
trim(): It use to remove whitespace or any predefine character from both(left & right) side of string.

Syntax:
ltrim(string_vaiable, charlist)
rtrim(string_vaiable, charlist)
trim(string_vaiable, charlist)

For Example,
$strVal = "!Welcome To India!";

echo ltrim($strVal, "!");
echo rtrim($strVal, "!");
echo trim($strVal, "!");

Answer is:
Welcome To India!
!Welcome To India
Welcome To India

str_replace()
It is used to replace  character or word to some other character or word in a string. It is a case sensitive(means tata & TATA is two different value).
Syntax:
str_replace(search_char, replace_char, string_variable)

For Example:
$strVal = "Welcome to india";
$strVal = str_replace("india", "INDIA", $strVal);
echo $strVal;

Answer is:
Welcome to INDIA

No comments:

Post a Comment

Copyright © 2019 Tech Location BD. All Right Reserved