PHP regex preg_match_all for string


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:
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);

假设所有部分都不能包含|。但是即使可以,正则表达式也帮不上什么忙。

如果您想继续使用regex以避免手动循环,那么我建议使用此语法而不是使用['w'W]*语法并考虑可读性:

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

使用显式否定字符类会更健壮一些。(我假设标题和url都不能包含|)