开发者

PHP: question about preg_replace()

i have found this:

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

Anyone can tell me what exactly d开发者_开发知识库o that? There is no information about what '/\W+/' means..

Regards

Javi


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜