简体   繁体   中英

How to get the specific string from the HTML tag code and check existence of <img> tag in a string?

I've two HTML codes. One of them is definitely going to present in a variable $text as follows :

//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>;

If first HTML code is present the variable $type should contain the value 'file' like $type = 'file';

If second HTML code is present the variable $type should contain the value 'image' like $type = 'image';

I want to achieve this using HTML Parsing.

In first case, I want the string 'file' from the class attribute of first anchor tag class="comment_attach_file_link"

In second case, I want the string 'image' only if the <img> tag is present in the HTML code.

How should I do this in an efficient way in PHP? Please help me.

Thanks.

You can use strpos() to do that:

<?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';
}

?>

It can be done easily through jquery "$('#id').attr('class')". You will get the class value. The same with the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM