Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all non-alphanumeric and non-space characters from a string in PHP?

Tags:

php

I want to remove all non-alphanumeric and space characters from a string. So I do want spaces to remain. What do I put for a space in the below function within the [ ] brackets:

ereg_replace("[^A-Za-z0-9]", "", $title);

In other words, what symbol represents space, I know \n represents a new line, is there any such symbol for a single space.

like image 431
Daniel Avatar asked Mar 23 '10 19:03

Daniel


People also ask

How do I remove all non alphanumeric characters from a string?

To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.

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

Does Alnum include spaces?

Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.

How do you remove all non alphanumeric characters from a string excel?

Select the range that you need to remove non-alphanumeric characters from, and click Kutools > Text > Remove Characters. 2. Then a Delete Characters dialog box will appear, only check Non-alphanumeric option, and click the Ok button. Now all of the non-alphanumeric characters have been deleted from the text strings.


2 Answers

Just put a plain space into your character class:

[^A-Za-z0-9 ]

For other whitespace characters (tabulator, line breaks, etc.) use \s instead.

You should also be aware that the PHP’s POSIX ERE regular expression functions are deprecated and will be removed in PHP 6 in favor of the PCRE regular expression functions. So I recommend you to use preg_replace instead:

preg_replace("/[^A-Za-z0-9 ]/", "", $title)
like image 70
Gumbo Avatar answered Oct 02 '22 17:10

Gumbo


If you want only a literal space, put one in. the group for 'whitespace characters' like tab and newlines is \s

like image 41
Chibu Avatar answered Oct 02 '22 16:10

Chibu