Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace all special characters except underscore and period in php?

Tags:

regex

php

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 ..

like image 806
maniteja Avatar asked Jan 22 '14 07:01

maniteja


People also ask

How can I replace special characters in a string in PHP?

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.

How do I remove special characters except?

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.

How can I remove multiple special characters from a string in PHP?

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 (” “).

How do you replace special characters in regex?

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]+", "")


1 Answers

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.

like image 57
falsetru Avatar answered Oct 23 '22 09:10

falsetru