note 71233 deleted from function.strpos by nlopess
| From: | nlopess@php.net | Date: | Tue, 21 Nov 2006 18:52:04 +0000 |
| Subject: | note 71233 deleted from function.strpos by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-119955@lists.php.net to get a copy of this message | ||
Note Submitter: Dan Kempster (dankempster at gmail dot com)
----
I have two notes I would like to make:
1. admin at xylotspace dot com created a function that I was in search for, thank you bye the way.
However the function didn't work, it returns too much data. For example I had
<a href="http://www.google.co.uk"
title="Search Engine">Google</a>
and parsed it through the function only wanting the value of the href attribute by using
'href='" as the beginning marker and '"' (Speech Mark) as the end
marker, but it returned:
http://www.google.co.uk" title="Search
Engine">Google
So this is the revised function that does work:
<?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, $middle_pos);
$middle = substr($source, $middle_pos, $ending_pos - $middle_pos);
return $middle;
}
?>
2. My second note is that I have expanded on the above function so that it will look for all
occurrences of the beginning and end marker and so return all the data between those markers in an
array.
<?php
function str_getData($haystack, $beginning, $ending, $initPos = 0) {
//Count the number of occurrences of $beginning
$count = substr_count($haystack,$beginning);
//This will store all the wanted date
$wantedDate = array();
if($count > 0){
for($x=0; $x < $count; $x++){
//Get the char position for the first char of $beginning in $source
$beginningPos = strpos($haystack, $beginning, $initPos);
//Get the char position of the start of the data that is wanted
$middlePos = $beginningPos + strlen($beginning);
//Get the char position of the end of the data that is wanted
$endingPos = strpos($haystack, $ending, $middlePos);
//Fetch the wantted data
$wantedData[] = substr($haystack, $middlePos, $endingPos - $middlePos);
//Set the $initPos to $endingPos so we don't find this one again
$initPos = $endingPos;
}
}
return $wantedData;
}
?>
I use this for searching for URLs within a string.
For example:
<?php
$str = '
<a href="http://www.tjs.co.uk" title="TJS
Home Page">TJS Online Ltd</a>
<a href="http://www.google.com"
title="Google Search Engine">Google</a>
<a href="http://www.php.net" title="PHP.net
home page">PHP.net</a>
';
echo("<pre>".print_r(str_ getData
($str,'href="','"'),1)."</pre>");
?>
This will echo out
Array
(
[0] => http://www.tjs.co.uk
[1] => http://www.google.com
[2] => http://www.php.net
)