簡體   English   中英

PHP正則表達式preg_match_all用於字符串

[英]PHP regex preg_match_all for string

我有以下字符串:

關鍵字|標題| HTTP://example.com/

我想使用PHP函數

preg_match_all ( $anchor, $key, $matches, PREG_SET_ORDER) )

目前

$anchor='/([\w\W]*?)\|([\w\W]*)/';

我得到$ matches數組:

Array
(
    [0] => Array
        (
            [0] => keyword|title|http://example.com/
            [1] => keyword
            [2] => title|http://example.com/
        )

)

我想得到

matches[1]=keyword
matches[2]=title
matches[3]=http://example.com

我如何修改$ anchor才能實現此目的?

最簡單的方法是使用explode()而不是正則表達式:

$parts = explode('|', $str);

假設所有部件都不能包含| 但是,如果可以的話,正則表達式也不會幫助您。

如果您想繼續使用正則表達式來避免手動循環,那么建議您在使用的[\\w\\W]*語法上使用此正則表達式,以提高可讀性:

$anchor = '/([^|]*) \| ([^|]*) \| ([^\s|]+)/x';

顯式否定字符類的功能更強大。 (我假設標題和url都不能包含| 。)

暫無
暫無

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

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