Welcome to WebmasterWorld Guest from 54.162.168.187

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Preg replace all except

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

Full Member

10+ Year Member

joined:June 16, 2004
posts:232
votes: 0


How to preg_replace all expect (A_Za-z0-9 and the blank space ' ')
5:43 am on Jan 13, 2008 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 16, 2004
posts: 96
votes: 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)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:July 12, 2007
posts:766
votes: 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.

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members