当我用preg_match编写代码时。喜欢这个
$string = <<<ETO
<svg "[^>]*? width="480.24px" height="360px" viewBox="0 0 480.24 360" enable-background="new 0 0 480.24 360" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
ETO;
preg_match('/<svg[^>]*?width=['|"]{1}(.*?)['|"]{1}[^>]*?>/is', $string, $svginfo);
$svginfo
为空。
对此感到抱歉。我知道[^>]*?
不应该出现在 svg 中。 但是当有人发布此内容时,我需要从此内容中获取宽度信息。
谁能解释一下如何做到这一点?
在在线正则表达式测试器上进行测试,它告诉我:
\ matches the character literally (case insensitive)
1 matches the character 1 literally (case insensitive)
如果我在字符串中间使用1
,它说:
1 matches the same text as most recently matched by the 1st capturing group
这意味着您将找到匹配的结束语,这似乎是您想要做的。
哦,还有扎尔戈。
更新:
啊,这是扎尔戈问题。问题是您要确保不会跳过整个<svg .... >
标签,以便<svg>width="99"
被拒绝。一个简单有效的 HTML 模式是:
<svg name=">" width="42">
捕获此和类似变体的正则表达式很快就会失控;正确的方法是使用HTML解析器;这是一篇关于如何做到这一点的文章。