【问题标题】:preg_split shortcode attributes into arraypreg_split 短代码属性到数组中
【发布时间】:2015-05-02 18:13:17
【问题描述】:

我想通过“preg_split”将简码解析成数组。

这是示例短代码:

[contactform id="8411" label="这是\"第一个标签" label2='这是第二个\'标签']

这应该是结果数组:

大批 ( [id] => 8411 [label] => 这是 \" 第一个标签 [label2] => 这是第二个 \' 标签 )

我有这个正则表达式:

$atts_arr = preg_split('~\s+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$) ~', trim($shortcode, '[]'));

不幸的是,这仅在没有转义引号 \'\" 时才有效。

提前谢谢!

【问题讨论】:

  • preg_split 不是要走的路,如果需要确保结果的连续性,请使用preg_match_all\G 锚。
  • 我不知道 Casimir et Hippolyte 是否给出了正确的答案。但这是一个非常困难的问题。我在类似情况下通过使用json格式的参数解决了它

标签: php regex quotes shortcode preg-split


【解决方案1】:

使用preg_split 并不总是很方便或合适,尤其是当您必须处理转义引号时。因此,更好的方法是使用preg_match_all,例如:

$pattern = <<<'EOD'
~
(\w+) \s*=
(?|
    \s* "([^"\\]*(?:\\.[^"\\]*)*)"
  |
    \s* '([^'\\]*(?:\\.[^'\\]*)*)'
# | uncomment if you want to handle unquoted attributes
#   ([^]\s]*)
)
~xs
EOD;

if (preg_match_all($pattern, $yourshortcode, $matches)) 
    $attributes = array_combine($matches[1], $matches[2]);

该模式使用分支重置功能 (?|...(..)...|...(...)..) 为每个分支的捕获组提供相同的编号。

我在评论中谈到了\G 锚点,如果当前位置紧接在最后一场比赛之后,则此锚点成功。如果您想同时从头到尾检查短代码的语法,它会很有用(否则它完全没用)。示例:

$pattern2 = <<<'EOD'
~
(?:
    \G(?!\A) # anchor for the position after the last match
             # it ensures that all matches are contiguous
  |
    \[(?<tagName>\w+) # begining of the shortcode
)
    \s+
    (?<key>\w+) \s*=
    (?|
        \s* "(?<value>[^"\\]*(?:\\.[^"\\]*)*)"
      |
        \s* '([^'\\]*(?:\\.[^'\\]*)*')
    # | uncomment if you want to handle unquoted attributes
    #   ([^]\s]*)
    )
(?<end>\s*+]\z)? # check that the end has been reached
~xs
EOD;

if (preg_match_all($pattern2, $yourshortcode, $matches) && isset($matches['end'])) 
    $attributes = array_combine($matches['key'], $matches['value']);

【讨论】:

  • 这个答案解决了我的问题列表... preg_match_all 的方法真的很酷,谢谢
猜你喜欢
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2023-04-05
  • 1970-01-01
  • 2015-11-07
相关资源
最近更新 更多