note 103994 added to function.preg-match
| From: | mulllhausen at osu1 dot php dot net | Date: | Mon, 16 May 2011 08:57:51 +0000 |
| Subject: | note 103994 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179751@lists.php.net to get a copy of this message | ||
i do a fair bit of html scraping in conjunction with curl. i always need to know if i have reached
the right page or if the curl request failed. the main problem i have encountered is html tags
having unexpected spaces or other characters (especially the character sequence) between
them. for example when requesting a page with a certain manner set of post or get variables the
response might be
<a href='blah'><span>data data data</span></a>
but requesting the same page with different post/get variables might give the following result:
<a href='blah'>
<span>data data data</span>
</a>
to match both of these tag sequences with the same pattern i use the [\S\s]*? wildcard which
basically means 'match anything at all...but not if you can help it'
so the pattern for the above sequence would be:
<?php
$page1 = "........<a href='blah'><span>data data
data</span></a>.........";
$page2 = "........<a href='blah'>
<span>data data data</span>
</a>
........";
$w = "[\s\S]*?"; //ungreedy wildcard
$pattern = "/\<a href='blah'\>$w\<span\>data data
data\<\/span\>$w\<\/a\>/";
if(preg_match($pattern, $page1, $matches)) echo "got to page 1. match:
[".print_r($matches, true)."]\n";
else echo "did not get to page 1\n";
if(preg_match($pattern, $page2, $matches)) echo "got to page 2. match:
[".print_r($matches, true)."]\n";
else echo "did not get to page 2\n";
?>
----
Server IP: 117.55.229.1
Probable Submitter: 150.101.100.168
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/103994
Del: integrated -- https://master.php.net/note/delete/103994/integrated
Del: useless -- https://master.php.net/note/delete/103994/useless
Del: bad code -- https://master.php.net/note/delete/103994/bad+code
Del: spam -- https://master.php.net/note/delete/103994/spam
Del: non-english -- https://master.php.net/note/delete/103994/non-english
Del: in docs -- https://master.php.net/note/delete/103994/in+docs
Del: other reasons-- https://master.php.net/note/delete/103994
Reject -- https://master.php.net/note/reject/103994
Search -- https://master.php.net/manage/user-notes.php