note 69927 deleted from function.strpos by levim
| From: | levim@php.net | Date: | Tue, 22 Jul 2014 03:26:54 +0000 |
| Subject: | note 69927 deleted from function.strpos by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-200010@lists.php.net to get a copy of this message | ||
Note Submitter: admin at xylotspace dot com
----
Yay! I came up with a very useful function. This finds a beginning marker and an ending marker (the
first after the beginning marker), and returns the contents between them. You specify an initial
position in order to tell it where to start looking. You can use a while() or for() loop to get all
occurence of a certain string within a string (for example, taking all hyperlinks in a string of
HTML code)...
<?php
function get_middle($source, $beginning, $ending, $init_pos) {
$beginning_pos = strpos($source, $beginning, $init_pos);
$middle_pos = $beginning_pos + strlen($beginning);
$ending_pos = strpos($source, $ending, $beginning_pos + 1);
$middle = substr($source, $middle_pos, $ending_pos - $middle_pos);
return $middle;
}
?>
For example, to find the URL of the very first hyperlink in an HTML string $data, use:
$first_url = get_middle($data, '<a href="', '"', 0);
It's done wonders for scraping HTML pages with certain tools on my website.