正则表达的新手,非常困惑

时间:2014-04-20 17:16:31

标签: php regex

我是Regex的新手并且非常困惑,我已经阅读了其他问题,但仍然不明白该怎么做。

所以我有这个字符串:

$string = 'hello the image is <img src="wroot/1/15/5.jpg" alt="Image">';

我正试图让Regex提取图像标签,我该怎么做呢?

到目前为止我所做的事情(使用preg_match)是一团糟,所以我想我会在这里找到答案。

非常感谢。

此致

马特

编辑:

根据要求,这就是我想出来的。

$string = 'hello the image is <img src="wroot/1/15/5.jpg" alt="Image">';
$pattern = '/<img/src="^[a-zA-Z0-9_]{24,}$"/';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);

3 个答案:

答案 0 :(得分:2)

对于这个简单的例子,你可以轻松地做.. ..

preg_match('/src="([^"]*)"/', $string, $match);
echo $match[1]; // => "wroot/1/15/5.jpg"

如果您想要整个标签..

preg_match('/<[^>]*>/', $string, $match);
echo $match[0];

输出

<img src="wroot/1/15/5.jpg" alt="Image">

答案 1 :(得分:1)

您可以使用此正则表达式匹配html标记,如下所示:

</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>

输出:

<img src="wroot/1/15/5.jpg" alt="Image">

请参阅此regexpal链接:http://tinyurl.com/k3qqbhr

答案 2 :(得分:0)

马特,这是你的意思吗?

$string = 'hello the image is <img src="wroot/1/15/5.jpg" alt="Image">';
$regex = '~<img[^>]+>~';
if(preg_match($regex,$string,$m)) echo htmlentities($m[0]);

输出: <img src="wroot/1/15/5.jpg" alt="Image">

相关问题