gpt4 book ai didi

php正则表达式来匹配shorttags

转载 作者:搜寻专家 更新时间:2023-10-31 21:37:36 24 4
gpt4 key购买 nike

这很接近,但无法匹配连续的“属性”:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
preg_match_all('/\[((\w+)((\s(\w+)="([^"]+)"))*)\]/', $string, $matches, PREG_SET_ORDER);
print '<pre>' . print_r($matches, TRUE) . '</pre>';

返回以下内容:

Array
(
[0] => Array
(
[0] => [include file="bob.txt"]
[1] => include file="bob.txt"
[2] => include
[3] => file="bob.txt"
[4] => file="bob.txt"
[5] => file
[6] => bob.txt
)

[1] => Array
(
[0] => [another prop="val" attr="one"]
[1] => another prop="val" attr="one"
[2] => another
[3] => attr="one"
[4] => attr="one"
[5] => attr
[6] => one
)

[2] => Array
(
[0] => [tag]
[1] => tag
[2] => tag
)

)

其中 [2] 是标签名称,[5] 是属性名称,[6] 是属性值。

故障发生在第二个节点上 - 它捕获了 attr="one" 但没有捕获 prop="val"

TYIA。

(这仅适用于有限的、受控的使用 - 不是广泛分发 - 所以我不需要担心单引号或转义双引号)

最佳答案

不幸的是,没有办法像那样重复捕获组。就个人而言,我会使用 preg_match 来匹配标签本身(即删除正则表达式中所有额外的括号),然后 foreach 匹配你可以提取属性。像这样:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
preg_match_all('/\[\w+(?:\s\w+="[^"]+")*\]/', $string, $matches);
foreach($matches[0] as $m) {
preg_match('/^\w+/', $m, $tagname); $tagname = $tagname[0];
preg_match_all('/\s(\w+)="([^"]+)"/', $m, $attrs, PREG_SET_ORDER);
// do something with $tagname and $attrs
}

请注意,如果您打算用某些内容替换标签,您应该像这样使用preg_replace_callback:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
$output = preg_replace_callback('/\[\w+(?:\s\w+="[^"]+")*\]/', $string, function($match) {
preg_match('/^\w+/', $m, $tagname); $tagname = $tagname[0];
preg_match_all('/\s(\w+)="([^"]+)"/', $m, $attrs, PREG_SET_ORDER);
$result = // do something with $tagname and $attrs
return $result;
});

关于php正则表达式来匹配shorttags,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15491623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com