views:

54

answers:

4

Hi,

i have found this:

$text = preg_replace('/\W+/', '-', $text);

Anyone can tell me what exactly do that? There is no information about what '/\W+/' means..

Regards

Javi

+1  A: 

Looks like it replaces anything that isn't a 'word character' (letter, digit, underscore) and makes them hyphens.

Fosco
Yep. This is kinda URLizer. So you can use the value afterwards easily in an URL. For example, if I wanted to show Thread names in the URL (SEO) I would use this regex to convert `Why doesn't this work?!?` to `Why-doesn-t-this-work-`. Here it may be seen, it's not perfect. One should at least perform a `trim($url, '-')` on it afterwards.
nikic
+2  A: 

\W means a non-alphanumeric character, so anything other than a-z, A-Z, 0-9, or underscore.

This is standard for regular expressions, nothing specific to Php.

Here's a great tool for testing regular expressions:

http://www.gskinner.com/RegExr/

If you put \W+ in the box at the top you'll see what kinds of things it matches.

PS: Here's another tool that's simpler and cleaner, though perhaps not as feature rich:

http://rubular.com/

It includes a handy quick-reference for regular expressions at the bottom.

dreeves
+1  A: 

The preg family of functions uses Perl Compatible Regular Expressions, or PCRE. There's a nice cheat sheet for them here (PDF).

The \W means "any non word character", and the + would limit it to matches of one or more of the preceding character. "Word characters" are defined to be letters, digits and underscores, so \W would match characters that aren't one of those.

Your line of code would replace any occurrence of a set of characters that aren't word characters with a hyphen.

zombat
A: 

It's documented at http://es2.php.net/manual/en/regexp.reference.backslash.php (linked from the PCRE section of the PHP manual where preg_replace is explained).

Álvaro G. Vicario