Sometimes, you may need lớn remove special characters from a string for programming purposes. PHP has many built-in functions that can be used to lớn remove special characters from string data. This tutorial shows you how khổng lồ use a few different types of PHP built-in functions lớn remove special characters from a string.
Bạn đang xem: Remove special character from string in php
The str_replace() Function
One useful function that can be used to remove special characters from a string is the str_replace() function. The empty string must be used to lớn the replace character in this function khổng lồ remove the specified character. The syntax of this function is given below.
str_replace($search_str, $replace_str, $main_str <,$count >)
The str_replace() function can take four arguments. The first three arguments are mandatory, và the last argument is optional. The $search_str variable stores the value that will be searched in the string. The $replace_str variable stores the value that will be replaced from the string where the search text matches. You must use an empty string as the value of the $replace_str variable to remove the tìm kiếm text from the main string. The $count argument stores a value representing how many characters are replaced or removed.
Xem thêm: So Sánh Phần Mềm Dynamic Ax Now Dynamics 365 For Finance & Operations
Example: Using str_replace() to lớn Remove Special Characters
The following script shows the use of the str_replace() function khổng lồ remove a special character from a string of data. A user-defined function is declared in the script lớn perform the replace task. The hash(#), single quote(‘), and semicolon(;) characters are used as search characters, while the empty string is used as the replacement text for these characters.
/* The following script will remove somespecial characters from a string using str_replace()function*/ //Define the main string$mainstr = "#This is a sim"ple text;"; //The đầu ra before removeecho "Text before remove: ".$mainstr; //Call the function$replacestr = rm_special_char($mainstr); //Define the function to remove the spacial characterfunction rm_special_char($str) //Remove "#",""" và ";" using str_replace() function$result = str_replace( array("#", """, ";"), "", $str);//The output after removeecho "Text after remove: ".$result;?>
Output
The following đầu ra will appear after running the script given above. The value of the main text is printed before calling the str_replace() function, & the three special characters are removed from the main text và printed later.





Conclusion
This tutorial showed you four different ways of removing special characters from string data. I hope that this tutorial will help readers khổng lồ apply the functions provided in this article in their script.