Php 从带有属性的bb代码中提取图像url

Php 从带有属性的bb代码中提取图像url,php,Php,我有一些像这样的图像BB代码 [IMG]imageurlhere[/IMG] [IMG alt="image alt here"]imageurl[/IMG] [IMG alt="image alt here" title="image title"]imageurl[/IMG] 我用这个来获取图像url preg_match_all('/\[(img|IMG)\]\s*(https?:\/\/([^*\r\n]+|[a-z0-9\/\\\._\- !]+))\[\/(img|IMG)\]

我有一些像这样的图像BB代码

[IMG]imageurlhere[/IMG]

[IMG alt="image alt here"]imageurl[/IMG]

[IMG alt="image alt here" title="image title"]imageurl[/IMG]
我用这个来获取图像url

preg_match_all('/\[(img|IMG)\]\s*(https?:\/\/([^*\r\n]+|[a-z0-9\/\\\._\- !]+))\[\/(img|IMG)\]/Ui', $stringContainBbCode, $matches);
$urls = $matches[0];
但我只能在第一种情况下获取图像url。如何处理剩下的两个案例?

您可以使用
()?
块来检查可选内容,如您正在检查的
s?
中的“https”中的“s”。使用它检查
alt
属性是否存在。正则表达式应该是这样的:

/\[(img|IMG)(\s+alt="(?P<alt>[^"]+)")?(\s+title="(?P<title>[^"]+)")?\]\s*(https?:\/\/([^*\r\n]+|[a-z0-9\/\\\._\- !]+))\[\/(img|IMG)\]/Ui
/\[(img | img)(\s+alt=“(?P[^“]+)”)(\s+title=“(?P[^“]+)”)”?\]\s*(https?:\/\/([^*\r\n]+[a-z0-9\/\\\.\u\-!])\[\/(img)\]/Ui
注意,在这个正则表达式中,“alt”属性必须在“title”属性之前,如果两者都存在的话