簡體   English   中英

PHP,Regex和preg_match

[英]PHP, Regex and preg_match

我試圖從下面的字符串中提取匹配給定正則表達式的子字符串:

“Lorem ipsum dolor sit amet。 <xy:abc_ref d_id="1234"> Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet。 <xy:abc_ref d_id="1234">

正則表達式確實符合預期。 但是,出於某種原因,我只能訪問第一個解析的值。 即使計數器(count($ matches))表示有兩個結果,請參閱輸出。

$value = 'Lorem ipsum dolor sit amet. <xy:abc_ref d_id="1234">Lorem ipsum dolor sit amet. <xy:abc_ref d_id="5678">Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">';

來源:

function test($value)
{
    $RegEx = '/<xy:abc_ref ([^>]{0,})>/';       
    $n = preg_match($RegEx,$value,$matches);
    print("Results count: " . count($matches)."<br>");
    print("matches[0]: " . $matches[0]."<br>");
    print("matches[1]: " . $matches[1]."<br>");
    print("matches[2]: " . $matches[2]."<br>");
}
echo test($value);

輸出:

Results count: 2
matches[0]:
matches[1]: d_id="1234"
matches[2]: 

謝謝,LG

使用preg_match_all獲取所有匹配項。 preg_match只會返回第一個匹配項。 Count將返回兩個因為您捕獲一個組。

您必須使用preg_match_all

function test($value)
{
    $RegEx = '/<xy:abc_ref ([^>]{0,})>/';       
    $n = preg_match_all($RegEx,$value,$matches);
    print("Results count: " . count($matches[1])."<br>");
    print("matches[0]: " . $matches[1][0]."<br>");
    print("matches[1]: " . $matches[1][1]."<br>");
    print("matches[2]: " . $matches[1][2]."<br>");
}

暫無
暫無

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

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