php 获取指定 html 元素内第一个 img src 的 URL


php get URL of first img src inside of specified html element

我正在尝试找到最简单的方法,使用 PHP 获取指定元素/类中第一个图像的 URL,插入到 Open Graph og:image 和 Twitter twitter:image

<figure class="pictures">
<img src="/pictures/1.jpg"> <!-- it would be this here -->
<img src="/pictures/2.jpg">
<img src="/pictures/3.jpg">
</figure>
<meta property="og:image" content="<?php echo $og_image; ?>"/>

还想知道我是否可以让它通过回显获取相对 URL 前面的域,而不是在元标记中的回显前面硬编码它。

试试这个:

function gsb($string, $start, $end)
{
    $string = " " . $string;
    $ini    = strpos($string, $start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$pic=gsb($string,'src="','"');

我没有安装PHP,所以我实际上无法测试这段代码。但把它当作表达这个想法的伪代码。

<?php
    echo "<figure class='pictures'>";
    $URLS = array("/pictures/1.jpg","/pictures/2.jpg","/pictures/3.jpg");
    for($i=0;$i<count($URLS);i++) {
        echo "<img src='$URLS($i)'>";
    }
    echo "</figure>";
    echo "<meta property='og:image' content='$URLS(0)' />";
?>

这将为您提供所需的结果,使添加/删除 img 更容易,并且如果您的代码朝该方向构建,则允许您通过算法生成 img 列表。

要获取服务器的域,请结帐$_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME']

    with javascript like this BUT
    **by using php FOLLOW THIS LINK**
    [http://stackoverflow.com/questions/10130858/get-img-src-with-php][1]
        //this is jquery code for finding the SRC of first imahe 
        <script>
        //$( document ).ready(function() {//here we are playing with image so use
         $( window ).load(function() {

        var image_url = $( ".pictures img:first-child" ).attr("src");
        //in variable image_url the url of the image
        alert(image_url);
        });

        </script>

      [1]: http://stackoverflow.com/questions/10130858/get-img-src-with-php
    USING PHP:-
<?php     
//i just copy that code from upper link and make small change

    //if you are generating these image by loop then generate $html variable and use this code
    $html = '<img src="/arrow_down.png"><img src="/arrow_down1.png"><img src="/arrow_down2.png">';
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $xpath = new DOMXPath($doc);
    echo $src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"
?>