Php 使用preg_match_all返回部分图像';Wordpress中的url

Php 使用preg_match_all返回部分图像';Wordpress中的url,php,regex,wordpress,url,preg-match-all,Php,Regex,Wordpress,Url,Preg Match All,我试图修改下面的函数,使其返回post first image url,而不返回http://、域url和末尾的反斜杠,但我真的不知道在这种情况下如何处理regex。顺便说一下,我在Wordpress工作 这是函数返回的内容: http://www.domain.com/wp-content/uploads/2014/09/image.jpg function catch_first_image() { global $post, $posts; $first_img = '';

我试图修改下面的函数,使其返回post first image url,而不返回
http://
、域url和末尾的反斜杠,但我真的不知道在这种情况下如何处理regex。顺便说一下,我在Wordpress工作

这是函数返回的内容:
http://www.domain.com/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;
}
这就是我需要的:
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;
}
函数catch\u first\u image()
{
全球$员额,$员额;
$first_img='';
ob_start();
ob_end_clean();
$output=preg_match_all('//i',$post->post_content,$matches);
$first_img=$matches[1][0];
echo$first\u img;
}
对于正确的正则表达式的进一步解释,我们将不胜感激:) 提前谢谢

使用以下表达式:

~<img.+?src=['"]http://www\.domain\.com/([^'"]+)['"].*?>~i
~~i

我只是字面上匹配了
http://www.domain.com
在您引用的第一个捕获组之外。请注意,我将分隔符更改为
~
,因此不需要转义斜杠。您可能希望将其更改为
https?:/(?:www\)?
,以使事情更加灵活。别忘了避开经期。另外,我让你的点匹配所有重复都懒得让你在将来头疼(
+?
*?
)。

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

echo $matches[1][0];

+1感谢你没有我那么懒。我会让
*
变懒(事实上,如果删除了尾随的
,您甚至不需要最后一个),并使用不同的分隔符(粗体,因为您当前没有转义所有的
/
)。感谢您如此快速的响应!)只有一个小细节。现在编写函数的方式不仅是返回我请求的图像URL的一部分,还返回其后的所有内容,包括
alt
width
height
等属性。它应该在图像格式之后和结束双引号之前结束。但这也是我的错,我早该澄清的。非常感谢你,@Amir!:)现在它工作得很好!我真的需要学习如何处理这件事。这在PHP中似乎很重要。请检查我更新的答案。我不确定正则表达式是如何工作的,但Wordpress一直认为
~
符号是PHP错误。在functions.php文件中插入代码时,我可能出错:(表达式需要说明表达式的开始和结束时间..任何修饰符(
I
,不区分大小写)在结尾分隔符之后。我使用了
~
,因此不需要对表达式中的每个
/
进行转义。请记住,此字符串仍然需要在引号中:
preg\u match\u all(“~~I”,$post->post\u content,$matches);
是的,我就是这样使用的,但它不会返回任何内容:(
<img.+?https?://[^\/]+\/\K[^\"']+