我正在尝试修改下面的函数,以便它返回帖子第一个图像网址,不带 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/