dsxz84851 2013-07-31 23:59 采纳率: 100%
浏览 40

PHP Regex strtolower函数,用于维护引号内的文本大小写

I search a method to get a lower string but does not change the case of text within quotes.

The string :

SELECT * FROM UtilisateurApplicatif WHERE idUtilisateurApplicatif <> "-1" AND Identification = "TOTO" AND MotDePasse = "TotoTUTU" AND Actif = 1

The result why i want :

select * from utilisateurapplicatif where idutilisateurapplicatif <> "-1" and identification = "TOTO" and motdepasse = "TotoTUTU" and actif = 1
  • 写回答

1条回答 默认 最新

  • dotj78335 2013-08-01 00:21
    关注

    You can do this using preg_replace_callback that allows to apply a function on a match result:

    $subject = <<<'LOD'
    SELECT * FROM UtilisateurApplicatif
    WHERE idUtilisateurApplicatif <> "-1"
    AND Identification = "TOTO"
    AND MotDePasse = "Toto\"TUTU" AND Actif = 1
    LOD;
    
    $pattern = <<<'LOD'
    ~
    (?(DEFINE) 
        (?<DQuotedContent>
            (?> [^"\\]++ | (?:\\{2})++ | \\. )*
        )
    )
    " \g<DQuotedContent> " \K | [A-Z]++
    ~x
    LOD;
    
    $result = preg_replace_callback($pattern,
        function ($match) { return strtolower($match[0]); },
        $subject);
    print_r($result);
    

    Pattern explanation:

    The idea of the pattern is to match quoted parts before and remove them from the match result to not apply the strtolower.

    First I define a subpattern (DQuotedContent) with all the possible content between double quotes, ie:

    • all characters that are not a double quote or a backslash [^"\\]
    • all even number of backslashes (?:\\{2})++ (which can't escape anything)
    • escaped characters (an escaped double quote can't close a quoted string)

    The main part of the pattern is now easy to write:

    " \g<DQuotedContent> "      # quoted part
    \K                          # reset all that have been matched before
    |                           # OR
    [A-Z]++                     # uppercase letters
    

    Note that the \K is very useful since it remove the quoted part from the match. Thus the callback function don't have to know what have been matched to apply strtolower.

    Notice: I have written the pattern using the nowdoc syntax, a define section, a named subpattern, and the comment mode (~x) for more readability, but you can use instead the same pattern in a more compact version:

    $pattern = '~"(?>[^"\\\]++|(?:\\\{2})++|\\\.)*"\K|[A-Z]++~';
    

    Unlike the nowdoc syntax, the backslash must be escaped twice.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值