Sometimes, you may need to remove special characters from a string for programming purposes. PHP has many built-in functions that can be used to remove special characters from string data. This tutorial shows you how to use a few different types of PHP built-in functions to remove special characters from a string.

Đ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 the replace character in this function to 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, and 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 search 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 Remove Special Characters

The following script shows the use of the str_replace() function to remove a special character from a string of data. A user-defined function is declared in the script to 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 output 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 “#”,””” and “;” using str_replace() function$result = str_replace( array(“#”, “””, “;”), “”, $str);//The output after removeecho “Text after remove: “.$result;}?>

Output

The following output will appear after running the script given above. The value of the main text is printed before calling the str_replace() function, and the three special characters are removed from the main text and printed later.

Xem thêm:

*
*
*
*
*

Conclusion

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

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *