使用preg_match从文本中获取src

时间:2013-04-22 05:46:35

标签: php preg-match

我通过短代码将图像添加到WP网站:

[figure src="" url"" caption=""]

src是图片来源的地方,url是指向较大图片的链接(如果需要),caption是标题。

我正试图从上面得到src基于此代码:

$pattern = '/<img[^>]*src=\"?(?<src>[^\"]*)\"?[^>]*>/im';
preg_match( $pattern, $html, $matches ); 
if($matches['src']) {
    return $matches['src'];
}

但我想弄清楚如何获得[figure]匹配。

2 个答案:

答案 0 :(得分:1)

/\[figure(( src="(?<src>[^"]+)")?|( url="(?<url>[^"]+)")?|( caption="(?<caption>[^"]+)")?)*\]/i
  

[图url =&#34; http://example.com/large.gif" caption =&#34;我的标题&#34; SRC =&#34; HTTP://example.com/figure.gif"]

Array
(
    [0] => [figure url="http://example.com/large.gif" caption="my caption" src="http://example.com/figure.gif"]
    [1] => 
    [2] =>  src="http://example.com/figure.gif"
    [src] => http://example.com/figure.gif
    [3] => http://example.com/figure.gif
    [4] =>  url="http://example.com/large.gif"
    [url] => http://example.com/large.gif
    [5] => http://example.com/large.gif
    [6] =>  caption="my caption"
    [caption] =>  my caption
    [7] => my caption
)

答案 1 :(得分:0)

试试这个

$foo = [figure src="" url"" caption=""];
preg_match( '/src="([^"]*)"/i', $foo, $array ) ;
$finalStr = $array[0];
$explode = explode("=", $finalStr);
echo $explode[1];