【问题标题】:need a regular expression to get width and height from image url in php需要一个正则表达式从 php 中的图像 url 获取宽度和高度
【发布时间】:2013-04-17 06:37:05
【问题描述】:

我的图像类

$temp=<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">

我想从网址中获取宽度和高度,即width="180"height="105"

我已经使用了 src 部分

preg_replace('/<img\s.*?\bsrc="(.*?)".*?>/si', $temp, $matches);

$matches= 它包含像这样提取的 src

http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg

现在如何使用正则表达式或任何其他也接受的方法提取宽度和高度??

【问题讨论】:

    标签: php regex wordpress


    【解决方案1】:

    在 php 中使用 dom 类是一种更好的方法。更容易使用。 示例:http://sandbox.onlinephpfunctions.com/code/c6d89fc6e0803ac38a3bc1ea9c61e081c1b71f08

    $dom = new DOMDocument();
    $dom->loadHTML('<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">');
    
    $img = $dom->getElementsByTagName('img');
    
    $src= $img->item(0)->getAttribute('src'); 
    $width= $img->item(0)->getAttribute('width'); 
    $height= $img->item(0)->getAttribute('height'); 
    
    echo $src ."<br/>";
    echo $width."<br/>";;
    echo $height."<br/>";;
    

    【讨论】:

      【解决方案2】:

      我更喜欢为此使用 PHP 的 DOM 扩展,因为它更可靠并且知道如何正确解析 HTML,并且知道一些字符集。

      <?php
      
      $temp='<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">';
      
      $dom = new \DomDocument;
      $dom->loadHTML($temp);
      
      $img = $dom->getElementsByTagName('img')->item(0);
      
      // Note: Values are returned as strings, not as numbers
      $src = $img->getAttribute('src');
      preg_match('/(.+)-([0-9]+)x([0-9]+)\.jpg$/', $src, $matches);
      
      $width = $matches[2];
      $height = $matches[3];
      

      【讨论】:

        【解决方案3】:

        你可以这样做

        list($height, $width) = explode("x",substr(strrchr( $url , "-" ),1,-4));
        

        如果我理解错了,你需要从属性中获取,而不是图片的实际 url,那么

        $url= '<img class="alignnone wp-image-6" alt="2166105529_70dd50ef4b_n" src="http://192.168.1.12/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n-300x175.jpg" width="180" height="105">';
        
        echo substr(strstr( $url , "width" ),0,-1);
        

        会回应

        width="180" height="105"
        

        【讨论】:

          猜你喜欢
          • 2011-11-26
          • 1970-01-01
          • 1970-01-01
          • 2018-07-05
          • 2012-04-19
          • 1970-01-01
          • 2011-09-14
          • 2012-05-30
          • 2012-07-11
          相关资源
          最近更新 更多