Got more questions? Find advice on: ASP | SQL | XML | Windows
Welcome to RegexAdvice Sign in | Join | Help

Re: Matching only column names in SQL where clause (and not quoted parts)

  •  04-17-2007, 10:14 AM

    Re: Matching only column names in SQL where clause (and not quoted parts)

    docdawson:

    yea, i'm from germany and i posted the link in german without thinking about it. sorry.

    No problem at all. I thought you found out about me being from Germany by some German-English quirks in my original post. Big Smile

    docdawson:

    don't there is always an "=" behind the $search?

    In most cases there will be an SQL operator behind $search, it might be something like =, <, >, LIKE, ILIKE, ISNULL, perhaps a closing ")", but there are many more.

    But as you can see from my example in the first post $search might also be found on the right hand side of an operation. Example:

    Map

    searchreplace
    price withdrawal
    money credit

    Input

    "price <= money"

    Output

    "withdrawal <= credit"

    Here is what I'm using (reluctantly) right now, maybe it will be a solution for others or a start for finding a better solution:

    function parsePattern($text, $search, $replace) {

    $pattern = "/(?(?=[^']*\b$search\b)\b$search\b|.*?'.*?')/";

    return preg_replace_callback($pattern, create_function('$matches',
    'return ($matches[0] == "' . $search . '") ? "' . $replace . '" : $matches[0];') , $text);
    }

    I'll try to explain: The pattern does two different things, depending on a forward assertion. If it finds no single quote in front of the next $search, it matches $search, otherwise it matches/consumes up to the closing (second) quote. Matches will be either $search or something else. In the callback function I test if the match is $search. If so, I replace it with $replace, otherwise the "replacement" will be the match itself, effectively changing nothing.

    If there was a way to construct a look behind assertion, assuring that there is an even number of quotes in front of $search, I wouldn't need the callback.

    Now, if there's no better solution than to use a callback, I can live with that. But I'd be happy for your input regarding speed and effectiveness of the pattern.

    Another thing that might be helpful: If I would allow double quotes as well my pattern would be

    "/(?(?=[^'\"]*\b$search\b)\b$search\b|.*?(['\"]).*?\\1)/"

    Note that it does not check for backslash escaped quotes.

View Complete Thread