Jump to content

looping


avo

Recommended Posts

HI

 

Can anyone help me out here please

what i would like to do is loop through the given url ($url_fetched)

for more instances of the given parameters ($start_string to $end string)

the bellow code will echo our what it finds between start and end but i need it to keep looking for these instances until none are left then return false until then return the string ($extractedstring).

 

this is what i have so far

 

function split_string($url_fetched,$start_string,$end_string){
$string = $url_fetched;
$m1     = $start_string;
$m2     = $end_string;

$extractedstring = substr($string,strpos($string,$m1)+strlen($m1),(strpos($string,$m2,strpos($string,$m1)+strlen($m1))-(strpos($string,$m1)+strlen($m1))));
return $extractedstring ;

 

 

 

by just using this function as it is it will output something like.

 

$page = "http://www.phpfreaks.com"; 
<?=split_string ($page,'PHP' ,'your');?>

 

output:-

Freaks.com:

 

but if the page had multiple instances of PHP 'some text i want' your i would only get Freaks.com: as its the first instance

 

hope this made sense.

 

Regards. ;)

 

Link to comment
https://forums.phpfreaks.com/topic/83768-looping/
Share on other sites

There's a number of ways to approach this.  Using regexp is probably most efficient, but if you're not willing to learn the dark arts yet you can do it with strpos() and substr().  Try this (including the missing end of the function):

 

function split_string($url_fetched,$start_string,$end_string){
$string = $url_fetched;
$m1     = $start_string;
$m2     = $end_string;
        
        $extracted = array();
        while ($offset < strlen($string) {
                $m1_offset = strpos($string, $m1);
                $m2_offset = strpos($string, $m2);
                if ($m1_offset !== false) {
                        $extracted[] = substr($string, $m1_offset, ($m2_offset - $m1_offset));
                        $string = substr($string, $m2_offset + strlen($m2)); # Remove matched portion from input
                } else {
                        break; # Finish loop, no more mathes
                }
        }
        return $extracted;
}

 

I have not tested this code, but the algorithm should work.  Basically it chops off the matched portion after finding a match, ensuring that the next match will be found next time around the loop.

Link to comment
https://forums.phpfreaks.com/topic/83768-looping/#findComment-426303
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.