正则表达式将视频从自定义输入转换为 HTML

问题描述 投票:0回答:1

我目前正在尝试编写一个过滤器,它将转换一些简单的输入文本 例如 Markdown 或纯文本到一些 HTML 中。这个想法是赋予能力 最终用户将一些视频添加到内容中。所以输入可以包含简单的 Markdown 然后是一些看起来像这样的标签:

[video url:"https://www.youtube.com/watch?v=EkluES9Rvak" width=100% ratio='16/9'
autoplay:1 caption:"Lea Verou - Regexplained"]

我想在语法上相当软,并在属性之间允许

:
=
名称和值。和 HTML 一样,值可以是可选的单引号或双引号 解决空格或特殊字符的问题。这就是我开始挣扎的地方!

目前我用 PHP 编写了这个正则表达式:

/(?(DEFINE)
# This sub-routine will match an attribute value with or without the quotes around it.
# If the value isn't quoted then we can't accept spaces, quotes or the closing ] tag.
(?<attr_value_with_delim>(?:(?<delimiter>["']).*?(?:\k<delimiter>)|[^"'=\]\s]+))
)

\[
\s*video\s+
(?=[^\]]*\burl[=:](?<url>\g<attr_value_with_delim>))      # Mandatory URL
(?=[^\]]*\bwidth[=:](?<width>\g<attr_value_with_delim>))? # Optional width
(?=[^\]]*\bratio[=:](?<ratio>\g<attr_value_with_delim>))? # Optional ratio
(?=[^\]]*\bautoplay[=:](?<autoplay>\g<attr_value_with_delim>))? # Optional autoplay
(?=[^\]]*\bcaption[=:](?<title>\g<attr_value_with_delim>))? # Optional caption
[^\]]*
\]/guxs

你可以在这里测试它:https://regex101.com/r/hVsav8/1

我的问题:

  • 如何处理属性值中的

    ]
    问题?

  • 是否可以在没有引号的情况下获取价值?

    这不是很重要,因为我可以稍后用

    trim(..., '"\'')
    摆脱它 在回调中,但我很想看看是否有模式解决方案。

php regex filter pcre
1个回答
0
投票

定义:

(?(DEFINE)

# Match quote-delimited values

  (?<attr_value_with_delim>
    '(?:\\.|[^'])*'
  |
    "(?:\\.|[^"])*"
  )

# Match non-quote-delimited values

  (?<attr_value_without_delim>[^'"\s[\]]+)

# Match both types

  (?<attr_value>
    \g<attr_value_with_delim>
  |
    \g<attr_value_without_delim>
  )

# Match attr - value pairs in the following forms:
## attr:value
## attr=value
## attr:"value'[]=:"
## attr='value"[]=:'
## attr:"val\"ue"
## attr:'val\'ue'

  (?<attr_with_value>
    \s+[a-zA-Z]+[:=]\g<attr_value>
  )
)

实际匹配模式:

\[\s*                             # Opening bracket followed by optional whitespaces
video                             # Literal 'video'
\g<attr_with_value>*              # 0+ attribute - value pairs
(?:                               #
  \s+                             # Preceding whitespaces
  url[:=]                         # Literal 'url' followed by either ':' or '='
  (?:                             # 
    '\s*(?:\\.|[^'\s])+\s*'       # Single or double quote-delimited,
  |                               # space-surrounded (optional)
    "\s*(?:\\.|[^"\s])+\s*"       # URL that doesn't contain whitespaces
  |                               #
    \g<attr_value_without_delim>  # or a non-quote-delimited value
  )                               #
)                                 #
\g<attr_with_value>*              # 0+ attribute - value pairs
\s*\]                             # Optional whitespaces followed by closing bracket

这个正则表达式匹配一个视频符号,然后可以使用合法和非邪恶的方式进一步解析。事实证明,强烈建议不要使用正则表达式解析类似 HTML 的内容。

在 regex101.com 上尝试.

© www.soinside.com 2019 - 2024. All rights reserved.