0

I've searched and tested for hours, ready to give up. I have a html page that will change every now and then, it's structure is this....

100 or so lines of HTML
<div class="the start of the info I want">
500 lines of HTML that I want to extract
<div class="end of the info I want">
more lines of HTML

This is my code that does not work, well one of many I've tried.

<?php
$data = file_get_contents('http://www.soemstupidsite.xyz');
$regex = '#<div class="the start of the info I want">(.*?)<div
class="end of the info I want">#';
preg_match($regex,$data,$match);
print_r($match);
echo $match[1];
?>

Returns the following error:
PHP Notice: Undefined offset: 1 in /home/www/mycrapcode.php on line 7

What the hell am I doing wrong?

4
  • var_dump($match) to see what it returns Commented Jan 16, 2017 at 9:47
  • 1
    I assume the offset error is because the array is empty which is what print_r($match); shows. Commented Jan 16, 2017 at 9:49
  • echo $match[1]; this line throws the NOTICE, because the array $match is empty. Commented Jan 16, 2017 at 10:02
  • Yes I stated that above. Commented Jan 16, 2017 at 10:04

2 Answers 2

1
    $regex = '/<div class="the start of the info I want">(.*?)<div
class="end of the info I want">/s';
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, one rotten "s" missing. That fixed it. Thank you so much. If you are ever in the Aussie outback look me up I owe you a beer mate!
0

Please read something more about the regex modifiers/flags here.

The flag you need, is the s flag, so your selector would work on multiple lines.

Example with your code:

<?php
$data = file_get_contents('http://www.soemstupidsite.xyz');
$regex = '#<div class="the start of the info I want">(.*?)<div class="end of the info I want">#s';
preg_match($regex,$data,$match);
print_r($match);
echo $match[1];
?>

Also: the regex needs to be on 1 line, otherwise it won't work.

1 Comment

regex is on one line it wrapped when pasted. Thanks for the explanation of the 's' flag. Alexandr Malyita beat you by 6 minutes for the answer I've been looking for for half a day. I'll spot you a beer too if you're ever out my way!

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.