note 68226 deleted from function.strpos by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 16:35:16 +0000 |
| Subject: | note 68226 deleted from function.strpos by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154854@lists.php.net to get a copy of this message | ||
Note Submitter: wormss at wormss dot net
----
Im sure there are more efficient methods of this, but i use this alot when dealing with rss and was
proud of it.
<?
function data_from_element($needle,$haystack,$tags=FALSE) { // Expects two Strings, returns Array
$needle_start = "<".$needle.">"; $needle_end =
"</".$needle.">";
$array = array(); $pos_start = 0;
while(($pos_start = strpos($haystack,$needle_start,$pos_start)) !== false) {
$pos_end = strpos($haystack,$needle_end,$pos_start);
if($tags) $array[] = substr($haystack,$pos_start,$pos_end-$pos_start+strlen($needle_end));
else $array[] = substr($haystack,$pos_start + strlen($needle_start),$pos_end - $pos_start -
strlen($needle_start));
$pos_start++;
}
return $array;
}
d
//example
$rss = '<?xml version="1.0"?> <rss version="2.0">
<channel> <title>Example RSS</title> <description>Example RSS
Description</description> <link>http://example.com/rss/</link> <item>
<title>Example RSS 1</title> <link>http://example.com/rss/1.html</link>
<description>Example 1</description> </item> <item> <title>Example RSS
2</title> <link>http://example.com/rss/2.html</link>
<description>Example 2</description> </item> </channel> </rss>';
$items = data_from_elements(link,$rss); // $rss[0] => "http://example.com/rss/"
$items = data_from_elements(link,$rss,true); // $rss[0] => "<link> http://example.com/rss/ </link>"
?>