How to get all occurences of string in string?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

How to get all occurences of string in string?

Post by tomfra »

I am using this function to get a part of the html code from a web page, between the specified start & end tags. It works just fine. But it returns only the first occurence of the result string.

Code: Select all

function get_page_html($pagename, $start_tag, $end_tag){
  $page_content = file_get_contents($pagename);
    $from = strpos($page_content, $start_tag);
      $to = strpos($page_content, $end_tag);
  $page_part = substr($page_content, $from, $to - $from);
 return $page_part;
}
How should I alter the code to alter all occurences of the string between multiple start & end tags? To clarify - there can be something like this in the source html:

<!--Start_Tag-->
Some content
<!--End_Tag-->

<!--Start_Tag-->
Some different content
<!--End_Tag-->

Right now it returns only "Some content" but I'd like it to return both "Some content" & "Some different content" as one result string.

As always, any suggestions are welcome!

Tomas
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

The online manual has a very nice list of all of the string functions. I found this function when I looked there:

substr_count()
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

I was able to count the number of occurences of "needle" using some of the user contibuted code snippets at http://cz2.php.net/manual/en/function.strpos.php , but none of the ways to actually output the multiple needles that I tried worked.

Tomas
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

look into [php_man]preg_match_all[/php_man] and count the matches with [php_man]count[/php_man]
Post Reply