In this article, you going to see how to remove ampersand from String PHP in a step by step in a simple way with example.
If you are looking for this topic then you are at a right place.
Let’s start with the topic to remove ampersand from String PHP.
There any many methods to remove ampersand.
Method 1: Using function called str_replace
function.
It is a function, used to replace some characters with some other characters.
Following are the rules for string replace function.
- In array, the string is searched and returns an array.
- Next is inside an array, the string is get searched and find and replace performed with every array element.
- For every find value, the string is get replaced in case of a find is an array and replace is a string.
The important point regarding string replace function is a case sensitive.
Syntax for function called str_replace
function.
str_replace(find,replace,string,count)
Below is the detailed information regarding syntax.
Parameter | Information |
find | It is Required. Represent the value to find |
replace | It is Required. Represent the value to replace the value in find |
string | It is Required. Represent String which is to be searched |
count | It is optional. Count number of replacements |
Below is code snippet from which you can understand how to remove ampersand.
<?php
$str = 'product=1&qty=1';
$resStr = str_replace('&', '&', $str);
echo $resStr;
// OUTPUT:
// product=1&qty=1
?>
Method 2 : Using Function called htmlspecialchars_decode()
function.
It is a function which convert the predefined HTML entities to characters.
Below are some of HTML entities that will be decoded are:
& becomes & (ampersand)
" becomes " (double quote)
' becomes ' (single quote)
< becomes < (less than)
> becomes > (greater than)
Syntax for the function called htmlspecialchars_decode
function are as follow as:
htmlspecialchars_decode(string,flags)
Detailed information regarding syntax.
Parameter | Description |
string | It is Required. Represent String which is to be decode |
flags | It is Optional. Represent how to handle quotes |
Below is code snippet for removing ampersand using htmlspecialchars_decode
function.
<?php
$str = "This is simple & meaningfull text.";
echo htmlspecialchars_decode($str);
//OUTPUT
// This is simple & meaningfull text.
?>
Conclusion:
Finally, we have done with point how to remove ampersand from String PHP.
I hope you like this article and if you feel like we missed out on anything, please comment below.