Welcome to WebmasterWorld Guest from 54.166.46.226

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Preg replace all except

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

10+ Year Member



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

10+ Year Member



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)

WebmasterWorld Senior Member 5+ Year Member



$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.