homepage Welcome to WebmasterWorld Guest from 54.197.171.109
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
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
BlackRaven




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

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

 

venelin13




msg:3547005
 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".

PHP_Chimp




msg:3547296
 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