Extracting URL from a link containing a specific string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mike809
    New Member
    • Aug 2011
    • 5

    Extracting URL from a link containing a specific string

    I'd like to get address of certain links with desired text. Let's say I want to get links containing a word "BMW".

    Code:
    <a href="http://abc.com/xxxx">Dodge</a>
    <a href="http://abc.com/a123.php">Used [B]BMW[/B] card</a>
    <a href="http://xyz.com/ferrari">Brand new Ferraris</a>
    <a href="http://xyz.com/vjklj"><img src="pic.jpg" />Luxurious [B]BMW[/B]s</a>
    The link can only contain a text or a text and an image.

    Is there any way how to do that without using regular expressions?
  • milesmajefski
    New Member
    • Aug 2011
    • 10

    #2
    Code:
    <html>
    <head><title>Find Links with BMW in them</title>
    </head>
    <body>
    <?php
    
      $my_links = array();
      $example_links =
       '<a href="http://abc.com/xxxx">Dodge</a> 
        <a href="http://abc.com/a123.php">Used BMW card</a> 
        <a href="http://xyz.com/ferrari">Brand new Ferraris</a> 
        <a href="http://xyz.com/vjklj"><img src="pic.jpg" />Luxurious BMWs</a>';
      
      $my_pos = strpos($example_links, '<a');
      
      while ($my_pos !== False)
      {    
    	$anchorBeg = strpos($example_links, '<a', $my_pos); 
    	$anchorEnd = strpos($example_links, '/a>', $anchorBeg) + 2;
        $cut_length = $anchorEnd - $my_pos + 1;  
        $myStr = substr( $example_links, $anchorBeg, $cut_length );
    	if (strpos($myStr, "BMW") !== False)
    	
    	  $my_links[] = $myStr;
    	
    	$my_pos = strpos($example_links, '<a', $anchorEnd);
      }//end while
      
      //ouput
      $count = 0;
      foreach( $my_links as $str )
      {
        echo "<br />Link #$count: ";
    	echo $str;
    	$count++;
      }  
    ?>
    
    
    </body>
    </html>

    Comment

    • mike809
      New Member
      • Aug 2011
      • 5

      #3
      Thank you very much, I'm interested in parsing out the URLs only, so I'll probably do that the same way you did it with the A tags. That means finding >href="< and >"< and then use substr() function.

      Comment

      Working...