douchuo0730 2010-07-10 16:55
浏览 343
已采纳

用于匹配字符串中的双引号和/或单引号字符串的PHP正则表达式

I'm working on a template class and I've an issue when trying to parse out a list of quoted strings from a string argument list. Take for example the string:

$string = 'VAR_SELECTED, \'Hello m\'lady\', "null"';

I'm having a problem coming up with a regex that extracts the string "Hello m'lady" and "null". The closest I have got is

$string = 'VAR_SELECTED, \'Hello m\'lady\', "null", \'TE\'ST\'';
preg_match_all('/(?:[^\']|\\\\.)+|(?:[^"]|\\\\.)+/', $string, $matches);
print_r($matches);

Which outputs:

Array
(
    [0] => Array
        (
            [0] => VAR_SELECTED, 
            [1] => 'Hello m'lady', 
            [2] => "null", 
            [3] => 'TE'ST'
        )

)

However a more complex case of:

$string = 'VAR_SELECTED, \'Hello "Father"\', "Hello \'Luke\'"';
preg_match_all('/(?:[^\']|\\\\.)+|(?:[^"]|\\\\.)+/', $string, $matches);
print_r($matches);  

outputs:

Array
(
    [0] => Array
        (
            [0] => VAR_SELECTED, 
            [1] => 'Hello 
            [2] => "Father"
            [3] => ', 
            [4] => "Hello 
            [5] => 'Luke'
            [6] => "
        )

)

Can anyone help me solve this problem? Are multiple regexes the way forward?

Edit Maybe it would be easier to replace the commas within the strings with a placeholder and then break apart the strings with an explode?

Edit 2 Just thought of a simple insecure option (that I am not going to use), but generates an E_NOTICE error.

$string = 'return array(VAR_SELECTED, \'Hello , "Father"\', "Hello \'Luke\'4");';
$string = eval($string);
print_r($string);
  • 写回答

3条回答 默认 最新

  • dps43378 2010-07-10 18:49
    关注

    Try this:

    /(?<=^|[\s,])(?:(['"]).*?\1|[^\s,'"]+)(?=[\s,]|$)/
    

    Or, as a PHP single-quoted string literal:

    '/(?<=^|[\s,])(?:([\'"]).*?\1|[^\s,\'"]+)(?=[\s,]|$)/'
    

    That regex yields the desired result, but I think you're going about this wrong. Usually, if a quoted string needs to contain a literal quote character, the quote is escaped, either with a backslash or with another quote. You aren't doing that, so I had to use a fragile hack based on lookarounds. Are you sure the data isn't supposed to look like this?

    $string = 'VAR_SELECTED, \'Hello m\\'lady\', "null"';
    
    $string = 'VAR_SELECTED, \'Hello "Father"\', "Hello \\'Luke\\'"';
    

    Come to think of it, doesn't PHP have built-in support for CSV data?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题