[英]php regular expression to match shorttags
這很接近,但無法匹配連續的“屬性”:
$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;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.