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.

Ravistm
  • 2,163
  • 25
  • 25
  • 2
    Why you can't use `DOMDocument`? – Justinas Apr 21 '17 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](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – Pred Apr 21 '17 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 – Ravistm Apr 21 '17 at 13:36
  • the quotes must be the same, can't you see – Deadooshka Apr 21 '17 at 14:17
  • dont use regex for parsing html, the world will likely explode – DevDonkey Apr 21 '17 at 14:54

1 Answers1

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 );
MahdiY
  • 1,269
  • 21
  • 32
  • 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 Apr 22 '17 at 03:34
  • 1
    @Ravistm Code updated! now match tags with **bold**class=viewBuyButt**bold** – MahdiY Apr 22 '17 at 04:30