Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

I want to remove any type of special characters in a string like this:

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

Output Required:

This is a demo String Need to format this

How to do this using REGEX?

like image 531
Sukanta Paul Avatar asked May 30 '12 05:05

Sukanta Paul


1 Answers

Check for any repeated instance of a non-number, non-letter character and repeat 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 ^
 a-z    # 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
like image 171
Sampson Avatar answered Sep 30 '22 15:09

Sampson