homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Preg replace all except

 11:07 pm on Jan 12, 2008 (gmt 0)

How to preg_replace all expect (A_Za-z0-9 and the blank space ' ')



 5:43 am on Jan 13, 2008 (gmt 0)

Here is an example:

$pattern = "/[^\d\w\s]/";
$replacement = "*";
$subject = "1 Main str, #5";

echo preg_replace($pattern, $replacement, $subject);

The ^ symbol negate a class. Right after this symbol we put the classes:

\d - digits
\w - words
\s - space

So, it reads as: "replace with * all the symbols from $subject, which are not digits, words and spaces".


 7:28 pm on Jan 13, 2008 (gmt 0)

$pattern = "/[^\d\w\s]/";

As said \s is 'space', not just a single space, but 'whitespace' so things like tab are included in \s.
So if you dont want general whitespace then use -

/[^\d\w ]/"

\w is a-zA-Z_ so there is also the _ in there. So if you are bothered about having that in your expression then you need -

"/^[\d a-z]/i"

i so you dont have to type the upper case letters as well

Have a read through the Pattern Syntax [uk.php.net] to see exactly what is getting excluded. As \w depends on the locale set, so if your server is in France but you are expecting a-z as 'word' then that isnt all you are going to get, as some of the accented letter will also be in the 'word' character class.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved