I'm looking for a simple replacement of [[wiki:Title]]
into <a href="/wiki/Title">Title</a>
.
So far, I have:
$text = preg_replace("/\[\[wiki:(\w+)\]\]/","<a href=\"/wiki/read/\\1\">\\1</a>", $text);
The above works for single words, but I'm trying to include spaces and on occasion special characters.
I get the \w+
, but \w\s+
and/or \.+
aren't doing anything.
Could someone improve my understanding of basic regex? And I开发者_JS百科 don't mean for anyone to simply point me to a webpage.
\w\s+
means "a word-character, followed by 1 or more spaces". You probably meant (\w|\s)+
("1 or more of a word character or a space character").
\.+
means "one or more dots". You probably meant .+
(1 or more of any character - except newlines, unless in single-line mode).
The more robust way is to use
\[wiki:(.+?)\]
This means "1 or more of any character, but stop at first position where the rest matches", i.e. stop at first right bracket in this case. Without ? it would look for the longest available match - i.e. past the first bracket.
You need to use \[\[wiki:([\w\s]+)\]\]
. Notice square brackets around \w\s
.
If you are learning regular expressions, you will find this site useful for testing: http://rexv.org/
You're definitely getting there, but you've got a couple syntax errors.
When you're using multiple character classes like \w and \s, in order to match within that group, you have to put them in [square brackets] like so... ([\w\s]+) this basically means one or more of words or white space.
Putting a backslash in front of the period escapes it, meaning the regex is searching for a period.
As for matching special characters, that's more of a pain. I tried to come up with something quickly, but hopefully someone else can help you with that.
(Great cheat sheet here, I keep a copy on my desk at all times: http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/ )
精彩评论