Re: Regular expression question

From: Date: Thu, 27 May 2004 21:54:40 +0000
Subject: Re: Regular expression question
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-187081@lists.php.net to get a copy of this message
Rob Ellis wrote:
On Thu, May 27, 2004 at 09:59:05AM -0700, Dan Phiffer wrote:
So I'm trying to implement a simple wiki-like syntax for hyperlinking. Basically I want to match stuff like [this], where the word 'this' gets turned into a hyperlink. I have that working, but I want to be able to escape the opening bracket, so that it's possible to do \[that] without having it match as a link. Here's what I've got: // Matches fine, but without escaping $pattern = " /
       \[          # Open bracket
       ([^\]]+?)   # Text, including whitespace
       \]          # Close bracket
/x "; // Throws an unmatched bracket warning $pattern = " /
       [^\\]       # Don't match if a backslash precedes
       \[          # Open bracket
       ([^\]]+?)   # Text, including whitespace
       \]          # Close bracket
/x "; // Ignores escaping: \[example] still matches $pattern = " /
       [^\\\]      # Don't match if a backslash precedes
       \[          # Open bracket
       ([^\]]+?)   # Text, including whitespace
       \]          # Close bracket
/x "; Nothing seems to change if I keep adding backslashes to that first matching thingy (i.e. the escaping still doesn't work). Any ideas?
Try negative lookbehinds... $pattern = '
     /
        (?<!\\\\) \[    # open [ not preceded by a backslash
        (.*?)           # ungreedy match anything
        (?<!\\\\) \]    # close ] not preceded by a backslash
     /x
'; - Rob
BTW, instead of un-greedy maych anything (.*?) You could use a negative group....of course to deal with \] as well you have to do alittle more: ([^\]]|[\\\\\]])* -- paperCrane <Justin Patrin>

« previous php.general (#187081) next »