note 69927 modified in function.strpos by danbrown

From: Date: Sun, 17 May 2009 16:34:06 +0000
Subject: note 69927 modified in function.strpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154849@lists.php.net to get a copy of this message
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. --was-- 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)... 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. http://php.net/manual/en/function.strpos.php

« previous php.notes (#154849) next »