php - 在 WordPress 中使用 preg_match_all 返回部分图像的 url

标签 php regex wordpress url preg-match-all

我正在尝试修改下面的函数,以便它返回帖子第一个图像网址,不带 http://、域名网址和末尾的反斜杠,但我真的不知道知道在这种情况下如何处理正则表达式。顺便说一句,我正在 WordPress 中工作。

这是函数返回的内容:
http://www.domain.com/wp-content/uploads/2014/09/image.jpg

这就是我需要的:
wp-content/uploads/2014/09/image.jpg

function catch_first_image()
{
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
    $first_img = $matches[1][0];

    echo $first_img;
}

非常感谢有关正确正则表达式的进一步解释:) 提前致谢!

最佳答案

<强> Live demo

$output = preg_match_all( "/<img.*https?:\/\/[^\/]+\/([^\"']+)[\"'].*/i", $post->post_content, $matches );

echo $matches[1][0];

说明:

.* => any character zero or more times
https? => http or https
[^\/]+ => any character other than / at least one time
[\"'] => double or single quote

关于php - 在 WordPress 中使用 preg_match_all 返回部分图像的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25876431/

相关文章:

javascript - 如何检索先前属性的名称属性

PHP、MySQL : Issue with bindParam

php - 如何消除 file() 返回的项目末尾的换行符?

python - 使用正则表达式在 python 中获取特定字符串之后的所有内容

java - 使用正则表达式获取指定查询字符串中 paramName 的 paramValue

ruby-on-rails - Capybara 测试页面是否有正则表达式

php - 多个密码登录 : Good OR Bad

javascript - Https(SSL 证书)阻止了我在 wordpress 网站上的媒体小部件

php - 将可变价格范围替换为 WooCommerce 3 中选择的变化价格

php - Yosemite 升级后本地 WordPress 环境中的 "Error establishing a database connection"