0

Hi i want to get Div's attribute value from a HTML content without using DOMDocument in PHP. here is my code:

<?php
$html = <<<HTML
  <div class='viewBuyButt' onclick="javascript:window.location='https://somelink.com?sdf=fhasldfss';return false;"></div>
HTML;        
?>

OUTPUT Expected:

https://somelink.com?sdf=fhasldfss

I tried with:

<?php
$pattern = '/<div class="viewBuyButt".*\sonclick="(.*?)">/';
preg_match($pattern, $html, $viewAllLink);
var_dump($viewAllLink);// but not getting output

any help will be greatly appreciated.

5
  • 2
    Why you can't use DOMDocument? Commented Apr 21, 2017 at 13:27
  • 2
    What is wrong with DOM? It is intended to do this. RegExp is not a big hammer and if it is, not everything is a nail. Anyways, you can go with SimpleXML or XMLReader as an alternative. Click Commented Apr 21, 2017 at 13:29
  • i have that option tried and its working. So i wanted to know if any other option which may be useful. Thanks for the help Commented Apr 21, 2017 at 13:36
  • the quotes must be the same, can't you see Commented Apr 21, 2017 at 14:17
  • dont use regex for parsing html, the world will likely explode Commented Apr 21, 2017 at 14:54

1 Answer 1

1

Try this:

$html = <<<HTML
<div class='viewBuyButt' onclick="javascript:window.location='https://1.com';return false;"></div>
<div class='No-viewBuyButt' onclick="javascript:window.location='https://mahdiy.ir';return false;"></div>
<div class='viewBuyButt' >onclick="javascript:window.location='https://2.com';return false;"></div>
<div class='viewBuyButt' onclick="javascript:window.location='http://3.com';return false;"></div>
HTML;

preg_match_all("/class='viewBuyButt'((?!(\>|\<)).)*location='(.*)'/", $html, $viewAllLink);
print_r( $viewAllLink );
Sign up to request clarification or add additional context in comments.

2 Comments

could you pls add class name also in the preg_match, its critical for me. It should only get location attribute of div with class=viewBuyButt
@Ravistm Code updated! now match tags with boldclass=viewBuyButtbold

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.