PHP单引号正则表达式

时间:2010-08-18 10:17:58

标签: php html regex

本主题是对PHP get image src

的评论

所以我们有一个带有代码的变量(只有图像):

$image = "<img src='http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&d=identicon&r=PG' height='32' width='32' alt=''/>";

我们如何获得此图像的src?我们应该将它扔到一些新变量中。

想要使用正则表达式,试过这个(不起作用):

preg_match('@src=\'([^"]+)\'@', $image, $src);

问题是 - 有单引号而不是双引号。

最后,我们必须得到:

$src = 'http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&d=identicon&r=PG';

寻找真正的正则表达式。


如果我使用'@src=\'([^"]+?)\'@',则print_r($src)会:

Array (
[0] => src='http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&d=identicon&r=PG'
[1] => http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&d=identicon&r=PG
)

不需要数组中的第一个值。

感谢。

1 个答案:

答案 0 :(得分:3)

表达式[^"]+正在贪婪。要在达到'后立即停止匹配,请使用[^"]+?

我认为你的意思是[^']+。写这个也可以解决你的问题。

最后,将$src分配给$src[1]以获取第一个分组表达式。

相关问题