How to remove all punctuation in a string, just get words separated by spaces in PHP

I want to remove any special characters in a string as follows:

This is, ,,, *&% a ::; demo +  String.  +
Need to**@!/// format:::::
 !!! this.`

Requires conclusion:

This is a demo String Need to format this

How to do it with REGEX?

+5
source share
4 answers

Check for any duplicate instance of a character other than a number that is not alphanumeric and repeating with a space:

# string(41) "This is a demo String Need to format this"
$str = trim( preg_replace( "/[^0-9a-z]+/i", " ", $str ) );

Demo: http://codepad.org/hXu6skTc

/ # Denotes start of pattern
[# Denotes start of character class
 ^ # Not, or negative
 0-9 # Numbers 0 through 9 (Or, "Not a number" because of ^
 az # Letters a through z (Or, "Not a letter or number" because of ^ 0-9
] # Denotes end of character class
+       # Matches 1 or more instances of the character class match
/       # Denotes end of pattern
i       # Case-insensitive, a-z also means A-Z
+14

:

preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);

, , .

:

$yourString = 'This is, ,,, *&% a ::; demo +  String.  + Need to**@!/// format::::: !!! this.`';
$newStr = preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
echo $newStr;

:

This is a demo String Need to format this

, , , :

[^a-zA-Z0-9 ]

. , ( ), :

preg_replace('#[^a-zA-Z0-9]+#', ' ', $yourString);
+4
$string = preg_replace('/[^a-z]+/i', ' ', $string);

You can also allow 'in your character class to have conjunctions such as don'tnot to turn into don t:

$string = preg_replace('/[^a-z\']+/i', ' ', $string);

You might also want to trim it to remove leading and trailing spaces:

$string = trim(preg_replace('/[^a-z\']+/i', ' ', $string));
+2
source
echo preg_replace('/[^a-z]+/i', ' ', $str); 
// This is a demo String Need to format this 
+2
source

All Articles