【问题标题】:Get Featured image from Posted Content从发布的内容中获取特色图片
【发布时间】:2016-04-10 00:04:27
【问题描述】:

我有一个博客系统,用户在帖子内容中输入图片网址,例如 ->

hey how are you <img src="www.example.com/image.png" style="height=100px;">

然后我想找到这个 [img src] 行并将其用作特色图像,如下所示-> www.example.com/image.png

这是我尝试过的: $content 是表单发布的内容

preg_match('/(<img .*?>)/', $content, $img_tag);
$feature = $img_tag[0];   // This preg_match finds img src tag and provide me
$regex = '~<img.*?src=[\'"](?:view-source:)?([^"\']+).*?\/?>~';

$featured = preg_replace($regex, "$1", $feature);

谁能在这里解决问题?

【问题讨论】:

  • 所以您只想从帖子中的第一个&lt;img&gt; 标记中获取src 属性?还是我错过了什么?

标签: php regex preg-replace preg-match


【解决方案1】:

如果您尝试提取内容中第一个&lt;img&gt; 标记的src 属性,您只需要这样:

preg_match_all('/<img.*src="(.*)"/', $content, $matches);

$featured = isset($matches[1][0]) ? $matches[1][0] : null;

现在让我解释一下这里发生了什么:

preg_match_all 匹配整个字符串,而 preg_match 停止在第一行,除非您添加 s 修饰符。

对于$matches数组,第一个索引代表匹配组。匹配组的数量是从表达式开头到组的( 的计数。 0 匹配整个表达式。所以$matches[1] 代表src 参数中匹配组的结果。

从该数组中,我们获取第一个元素,即内容中第一个匹配的img 标记的src 属性。

当然,内容中不必包含任何图像,这就是为什么您应该在尝试访问结果之前调用isset。

我希望这可以解释它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2017-01-13
    相关资源
    最近更新 更多