2013-04-22 218 views
0

充分利用文本中的src我通过短码将图像添加到一个WP网站:使用的preg_match

[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]比赛。

回答

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

[图URL = “http://example.com/large.gif” 标题= “我的标题” SRC =“HTTP://例子。 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 
) 
+0

这很有用,我可以问有没有什么方法可以去掉模式以获取src?我喜欢所有其他选项,但我只是为了src。 – Ahhhhhhhhhhhhhdfgbv 2013-04-22 06:36:59

+0

我的正则表达式是为了以随机顺序匹配属性而构建的。如果你只需要src,你可以使用'/\[figure.* src =“(? [^”] +)“。* \]/iU'来代替 – 2013-04-22 07:06:18

+0

感谢这两个表达式。 – Ahhhhhhhhhhhhhdfgbv 2013-04-22 07:16:21

0

试试这个

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

没有为我工作。 – Ahhhhhhhhhhhhhdfgbv 2013-04-22 05:57:03

+0

哎呀,我给$ array [1]。我用$ array [0]更新了我的答案,你现在可以尝试吗? – 2013-04-22 06:00:09

+0

你的回答是目前给我的'src = IMG.jpg',我只需要'IMG.jpg' – Ahhhhhhhhhhhhhdfgbv 2013-04-22 06:06:10