August 28 th

0

Text Between Strings PHP

Posted by Andy Bailey
1,388 views

here's a useful function that I found in the comments of a php.net function reference to quickly extract the text between two given strings, useful for parsing XML documents or HTML. I've used it to parse lotto results, XML favorites and grabbing <img> links by fopen'ing a HTML file.
$text is the string you want to parse
$s1 is the start string
$s2 is the end string

PHP:
  1. function get_between ($text, $s1, $s2) {
  2. $mid_url = "";
  3. $pos_s = strpos($text,$s1);
  4. $pos_e = strpos($text,$s2);
  5. for ( $i=$pos_s+strlen($s1) ; (( $i<($pos_e)) && $i <strlen($text)) ; $i++ ) {
  6. $mid_url .= $text[$i];
  7. }
  8. return $mid_url;
  9. }

for example if this is a string in the variable $line in a file you are parsing
"<img>http://www.imageurl.com/image.gif</img>"
you can extract the url by using the function like this

PHP:
  1. $imageurl=get_between($line,"<img>","</img>");




Popularity: 2% [?]

Category : Code

Related Posts

  • Write text to a .png with php
  • New top 3 scoreboard for Aqua Game
  • Stumbled - Stumbleupon Widget for Wordpress 2.2
  • Play Aqua Game and win a prize for the highest score
  • Updated code for Aqua game display
  • Beta testing CommentLuv 1.0
  • Excel tip: How to not show zero values for forumla result

  • No comments yet.

    Leave a comment

    13 online now
    the most online was 176
    elottery Ajax commentluv
    Sponsors
    available ad space available ad space available ad space available ad space available ad space available ad space