Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey Guys :-)

Is there a regex pro, who is able to give me any hints?

The target is:

don't allow things like this:

SQL
select 
*, 
table_name.* 
from 
table_name


but allow things like this:

SQL
select 
/* my special comment with a * inside */ 
table_name.id 
from 
/* my cool table */ 
table_name


My regex knowledge kept me alive, till this problem :-)

Is it even possible?
The target engine, the regex should run on is PHP 5.4+ < 7

What I have tried:

\bselect\b.*?(\*|\.\*).*?(?=\bfrom\b) and such (or other) things.

But this lookbehinds and lookaheads are disturbing my mind ;-)
Posted
Updated 19-Aug-16 11:29am
v2
Comments
Mohibur Rashid 18-Aug-16 20:30pm    
How about doing this in two step,
1. Strip all comment
2. do your work

1 solution

I think there is no other way to do it like this:

PHP
class SQLValidation
{

    const PATTERN_SQL_VALID_COMMENT = '~((\/\*).*?(\*\/))~ismu';
    const PATTERN_SQL_NOT_VALID     = '~\bselect\b.*?(\*|\.\*).*?(?=\bfrom\b)~ismu';

    /**
     * validates a sql string against * or .* in sql selectors
     * but allowes valid comments
     * 
     * @param string $queryString
     * @return bool true if there is any star selector in the queryString
     */
    public static function hasStarSelector($queryString)
    {
        $sql_without_comments = preg_replace(
           self::PATTERN_SQL_VALID_COMMENT, 
           '', 
           $queryString
        );
        return (
           preg_match(
             self::PATTERN_SQL_NOT_VALID, $sql_without_comments)
           ) ? 
        true : 
        false;
    }

 
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900