Php 正则表达式捕获组始终作为第一个

Php 正则表达式捕获组始终作为第一个,php,regex,Php,Regex,我有一个PHP正则表达式: https?:/(?:[a-z0-9]+\)?livestream\.com/(?:(accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?)|[^\s/]+/video\?clipId=([^\s&]+)([^\s/]+) 我喜欢将以下URL和结果进行匹配 http://original.livestream.com/bethanychurchnh = bethanychurchnh http://original.liv

我有一个PHP正则表达式:

https?:/(?:[a-z0-9]+\)?livestream\.com/(?:(accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?)|[^\s/]+/video\?clipId=([^\s&]+)([^\s/]+)

我喜欢将以下URL和结果进行匹配

http://original.livestream.com/bethanychurchnh = bethanychurchnh

http://original.livestream.com/bethanychurchnh/video?clipId=flv_b54a694b-043c-4886-9f35-03c8008c23 = flv_b54a694b-043c-4886-9f35-03c8008c23

http://livestream.com/accounts/142499/events/3959775 = accounts/142499/events/3959775

http://livestream.com/accounts/142499/events/3959775/videos/83958146 = /accounts/142499/events/3959775/videos/83958146

它工作得很好,但我有一个问题,捕获组是第二和第三的一些比赛。我希望捕获的字符串始终匹配为第一个捕获组。这可能吗?

您可以在正则表达式中使用分支重置:

https?:\/\/(?:[a-z0-9]+\.)?livestream\.com\/(?|(accounts\/[0-9]+\/events\/[0-9]+(?:\/videos\/[0-9]+)?)|[^\s\/]+\/video\?clipId=([^\s&]+)|([^\s\/]+))
                                             ^^

请参见以下内容的说明:

分支重置组内共享相同的捕获组。语法是
(?| regex)
,其中
(?|
打开组,regex是任何正则表达式。如果在分支重置组中不使用任何替换或捕获组,则其特殊功能将不起作用。然后它将充当一个正则表达式


其他可能性是,您可以使用
(?J)

$pattern = '~(?J)https?://(?:[a-z0-9]+\.)?livestream\.com/
(?:
    (?<id>accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?)
  |
    [^\s/]+/video\?clipId=(?<id>[^\s&]+)
  |
    (?<id>[^\s/]+)
)~x';

if (preg_match($pattern, $text, $m))
    echo $m['id'];
$pattern = '~https?://(?:[a-z0-9]+\.)?livestream\.com/ \K
(?:
    accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?
  |
    [^\s/]+(?:/video\?clipId=\K[^\s&]+)?
)~x';

if (preg_match($pattern, $text, $m))
    echo $m[0];