php - 带属性的正则表达式

标签 php regex parsing attributes preg-match-all

我想解析这种代码:

{articles mode="extrait" nb="3"}

我正在使用这个正则表达式:

@\{(articles)(?:(?:\s|\ )*(?:(\w+)="(\w+)"))*\}@

但它不起作用,当我执行 preg_match_all 时,这是带有 $matches 参数的 print_r 的结果:

Array (
    [0] => {articles mode="extraits" nb="3"}
    [1] => articles
    [2] => nb
    [3] => 3
)

我认为最后一个 * 应该可以获取所有属性,而不仅仅是最后一个。

您看到遗漏或不正确的地方了吗?

提前致谢

最佳答案

$instances = array();

@ preg_match_all( '/\{articles([^\}]+)\}/', $string, $articles );

if ( false === empty( $articles[1][0] ))
{
   foreach ( $articles[1] as $article )
   {
      @ preg_match_all( '/\b(\w+)="([^"]+)"/', $article, $arguments );

      if ( false === empty( $arguments[0][0] ))
      {
         $settings = array();

         foreach ( $arguments[0] as $index => $argument )
         {
            $settings[$arguments[1][$index]] = $arguments[2][$index];
         }

         $instances[] = $settings;
      }

      unset( $arguments );
   }
}

print_r( $instances );

关于php - 带属性的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13975515/

相关文章:

android - 如何在 Android 中转换以日期作为键的 JSON

php - 如何在php中获取内部数组元素的最大值

php - read_mailbox 在哪里(Facebook API)

javascript - 如何在javascript中用正则表达式测试一个字符串是否包含数字?

regex - 使用正则表达式过滤 slugs (url)

c# - 用于解析 C# 源代码的正则表达式

javascript - 使用 Ajax 调用将数组传递到 Javascript 代码中

php中的多个分隔符 explode

C# 使用正则表达式获取多个匹配项

parsing - 使用 JSOUP 或其他 HTML 解析器捕获 header 位置