如何获取在image.php中使用的SRC上一个和下一个图像


How to get the SRC previous and next images for use in image.php?

试图通过该函数的参数直接从函数previous_image_link()中删除图像是不可能的。因此,尝试简单地提取SRC:

<td style="background: url(
<?php
    $html = previous_image_link('full');
    preg_match_all('/<img [^>]*src=["|'']([^"|'']+)/i', $html, $matches);
    foreach ($matches[1] as $key=>$value) {
        echo $value;
    }
?>
) no-repeat center center; background-size: cover;">

然而,与预期的不同

<td style="background: url(/wp-content/uploads/2015/03/tiaurus.info_20150323125918.jpg") no-repeat center center; background-size: cover;">

获取

<td height="3166" class="attachment-full" alt="img_alt_text" src="/wp-content/blablabla/20150323125918.jpg" 8176"="">) no-repeat center center;background-size: cover;"&gt;
            </td>
) no-repeat center center;background-size: cover;">

在我的情况下,是否有必要使用preg_match_all?

或者有人能告诉我如何获得在image.php中使用的SRC上一个和下一个图像吗?

与其尝试使用正则表达式来提取URL,我认为您应该尝试对previous_image_link函数进行反向工程,以找到更直接的方法。

CCD_ 2本质上是围绕CCD_。一旦你看到相邻的图像是如何被提取的,就很容易编写一个函数来提取图像src,而不是格式化的链接:

function adjacent_image_src($prev = true) {
    $post = get_post();
    $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
    foreach ( $attachments as $k => $attachment ) {
        if ( $attachment->ID == $post->ID ) {
            break;
        }
    }
    $attachment_id = false;
    $src = false;
    if ( $attachments ) {
        $k = $prev ? $k - 1 : $k + 1;
        if ( isset( $attachments[ $k ] ) ) {
            $attachment_id = $attachments[ $k ]->ID;
            $src = wp_get_attachment_image_src( $attachment_id );
        }
    }
    return $src;
}

你也可以只返回$attachment_id,然后你就可以获得你需要的关于附件的任何信息。

您可以使用PHP函数pre_match并消除foreach循环。

preg_match('/ src=["'']([^'s]+)["'']/', $html, $matches);
echo $matches[1];

由于$html字符串只有一个src值可检索,因此preg_match就足够了。preg_match_all是为多个匹配而设计的。

此外,由于src=在字符串中是唯一的,我们可以将我们的模式缩小到以src=开头,并由双引号或单引号包裹的模式。["'']是一个字符类,它将匹配限制为一个双引号或单引号字符。(单引号是转义的,因为我使用单引号来分隔正则表达式字符串。)

括号()捕获一个值并将其添加到$matches数组中。

[^]是一个负字符类,换句话说,与这里列出的任何字符都不匹配。+匹配前一个字符中的一个或多个。所以[^'s]+只是简单地说,匹配一个或多个不是空格字符的字符。

给定:

$html = '<a href="/33279/retro-kartinyi-iz-skotcha-max-zorn"><img width="1600" height="900" class="attachment-full" style="width: 516px; height: 290px;" alt="Max Zorn" src="/wp-content/uploads/2015/03/tiaurus.info_20150323125854.jpg"></a>';

echo $matches[1];返回:

/wp-content/uploads/2015/03/tiaurus.info_20150323125854.jpg