Can any one please show me how i can replace all special characters in a string except the underscore and the period symbols.And also I've been trying to understand how to make this replace patterns reading the PHP
manual and its so confusing for a beginner like me so is there any other documentation or tutorial that is made easy for beginners so that i don't have to post another question like this and trouble you people every time i want to use this function?
preg_replace('/[^a-zA-Z0-9]/', '', $string);
this is what i have it replaces all the special characters but i want to except _
and .
.
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
Similarly, if you String contains many special characters, you can remove all of them by just picking alphanumeric characters e.g. replaceAll("[^a-zA-Z0-9_-]", ""), which will replace anything with empty String except a to z, A to Z, 0 to 9,_ and dash.
Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).
If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")
Put _
and .
to the negated set of characters ([^...]
):
$string = preg_replace('/[^a-zA-Z0-9_.]/', '', $string);
You should not omit $string = ..
because preg_replace
return replaced string. It does not change the string in place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With