簡體   English   中英

preg_match在更改其順序時與html屬性不匹配

[英]preg_match does not match html attribute on changing its order

我正在嘗試將某些xml標記與正則表達式匹配,這是我的php代碼

   $pattern = '#<xt:tag_name *(type\="(.+?)")? *(detail\="(.+?)")? ?/>#ui';
   $str = '<xt:tag_name type="1" detail="2" />';
   preg_replace($pattern,"type: $1, detail: $4",$str);
   preg_match($pattern,$str,$m);
   print_r($m);

我得到預期的結果

Array
(
    [0] => <xt:tag_name type="1" detail="2" />
    [1] => type="1"
    [2] => 1
    [3] => detail="2"
    [4] => 2
)

但是當我改變屬性的順序時

<xt:tag_name detail="2" type="1" />

比賽失敗

描述

該正則表達式將捕獲屬性typedetail而與屬性順序無關,只要它們位於xt:tag_name標記內即可。

<xt:tag_name\\b(?=\\s)(?=(?:(?!\\>).)*\\s\\btype=(["'])((?:(?!\\1).)*)\\1)(?=(?:(?!\\>).)*\\s\\bdetail=(["'])((?:(?!\\3).)*)\\3)(?:(?!\\>).)*\\>

在此處輸入圖片說明

展開說明

  • <xt:tag_name\\b驗證標簽名稱
  • (?=\\s)確保標記名稱后有空格
  • (?= type前瞻1。通過使用先行,您可以按任何順序捕獲屬性。
    • (?:(?!\\>).)*一次在標簽中移動一個字符,並防止正則表達式引擎退出該標簽,直到到達
    • \\s\\btype=屬性type
    • (["'])捕獲開放報價,稍后將使用它來匹配正確的結束標記
    • ((?:(?!\\1).)*)捕獲引號內的所有字符,但不包括相同類型的封裝引號
    • \\1匹配右引號
    • )關閉type的前瞻
  • (?=(?:(?!\\>).)*\\s\\bdetail=(["'])((?:(?!\\3).)*)\\3)對屬性執行完全相同的操作命名detail ,與type
  • (?:(?!\\>).)*匹配所有字符直到
  • \\>標簽的結尾

團體

第0組將具有完整的標簽,從左到右

  1. 將在type值的周圍使用開引號,這使正則表達式能夠正確匹配閉引號
  2. 將具有屬性type的值
  3. 將在detail值的周圍使用開放報價,這使正則表達式能夠正確匹配封閉報價
  4. 將具有屬性detail的值

PHP代碼示例:

輸入字串

<xt:tag_name UselessAttribute="some dumb string" type="1" detail="2" /><xt:tag_name detail="Things 'Punk' Loves" MoreUselessAttributes="1231" type="kittens" />

<?php
$sourcestring="your source string";
preg_match_all('/<xt:tag_name\b(?=\s)(?=(?:(?!\>).)*\s\btype=(["\'])((?:(?!\1).)*)\1)(?=(?:(?!\>).)*\s\bdetail=(["\'])((?:(?!\3).)*)\3)(?:(?!\>).)*\>/ims',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

火柴

$matches Array:
(
[0] => Array
    (
        [0] => <xt:tag_name UselessAttribute="some dumb string" type="1" detail="2" />
        [1] => <xt:tag_name detail="Things 'Punk' Loves" MoreUselessAttributes="1231" type="kittens" />
    )

[1] => Array
    (
        [0] => "
        [1] => "
    )

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

[3] => Array
    (
        [0] => "
        [1] => "
    )

[4] => Array
    (
        [0] => 2
        [1] => Things 'Punk' Loves
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM