Devone

How Can I Extract URLs Between Anchor Tags Using PHP?

Asked by Devone 2 years ago php url tags anchor


Csgs
0
 
This is great for parsing a message for URL's so that you can process them for character length when they are displayed on your screen:

/**
    Returns an array containing each of the sub-strings from text that
    are between openingMarker and closingMarker. The text from
    openingMarker and closingMarker are not included in the result.
    This function does not support nesting of markers.
  */
  function returnSubstrings($text, $openingMarker, $closingMarker) {
    $openingMarkerLength = strlen($openingMarker);
    $closingMarkerLength = strlen($closingMarker);

    $result = array();
    $position = 0;
    while (($position = strpos($text, $openingMarker, $position)) !== false) {
      $position += $openingMarkerLength;
      if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
        $result[] = substr($text, $position, $closingMarkerPosition - $position);
        $position = $closingMarkerPosition + $closingMarkerLength;
      }
    }
    return $result;
  }
$msg = "This is a string with a url in <a href="http://www.google.co.uk/search?q=php&num=100&hl=en&safe=off&start=200&sa=N">www.google.co.uk

$urls = returnSubstrings($msg,'">','</a>');

print_r($urls);

  // array (
  //   0 => 'http://www.google.co.uk/search?q=php&num=100&hl=en&safe=off&start=200&sa=N'
  // )
//

by Csgs 2 years ago

Answer this question

How Can I Extract URLs Between Anchor Tags Using PHP?

0 errors found:

 
0