【问题标题】:How to get the specific string from the HTML tag code and check existence of <img> tag in a string?如何从 HTML 标签代码中获取特定字符串并检查字符串中是否存在 <img> 标签?
【发布时间】:2015-04-06 13:18:33
【问题描述】:

我有两个 HTML 代码。其中之一肯定会出现在变量$text 中,如下所示:

//First HTML code 

$text = <a class="comment_attach_file_link" href="https://www.filepicker.io/api/file/vuHOZ3n8ToyvQUDQ03zi">vuHOZ3n8ToyvQUDQ03zi</a>

        <a class="comment_attach_file_link_dwl" href="https://www.filepicker.io/api/file/vuHOZ3n8ToyvQUDQ03zi">Download</a>;

    //Second HTML code
$text = <a title="" href="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws"><img src="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws" height="150px" width="150px"></a>

        <a href="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws" class="comment_attach_image_link_dwl">Download</a>;

如果存在第一个 HTML 代码,则变量 $type 应包含值“文件”,如 $type = 'file';

如果存在第二个 HTML 代码,则变量 $type 应包含值“图像”,如 $type = 'image';

我想使用 HTML Parsing 来实现这一点。

在第一种情况下,我想要第一个锚标签class="comment_attach_file_link"的类属性中的字符串'file'

在第二种情况下,仅当 HTML 代码中存在 &lt;img&gt; 标记时,我才需要字符串 'image'。

我应该如何在 PHP 中有效地做到这一点?请帮帮我。

谢谢。

【问题讨论】:

    标签: php html dom html-parsing


    【解决方案1】:

    您可以使用 strpos() 来做到这一点:

    <?php 
    
    $text = '<a title="" href="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws"><img src="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws" height="150px" width="150px"></a>
    
            <a href="https://www.filepicker.io/api/file/xdA3uDwdTWydvK7ISlws" class="comment_attach_image_link_dwl">Download</a>';
    
    if (strpos($text,'class="comment_attach_file_link"') !== false) {
        echo 'file';
    }
    elseif (strpos($text,'<img') !== false) {
        echo 'image';
    }
    
    ?>
    

    【讨论】:

      【解决方案2】:

      可以通过 jquery "$('#id').attr('class')" 轻松完成。您将获得班级价值。 与图像相同。

      【讨论】:

      • 我只想用 PHP 来做。
      猜你喜欢
      • 2012-01-19
      • 2018-12-23
      • 1970-01-01
      • 2018-06-08
      • 2012-11-07
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多