Extract urls between anchor tags using php


/ Published in: PHP
Save to your folder(s)

good for parsing a message for urls so you can process them for character length when displayed on screen


Copy this code and paste it in your HTML
  1. /**
  2.   Returns an array containing each of the sub-strings from text that
  3.   are between openingMarker and closingMarker. The text from
  4.   openingMarker and closingMarker are not included in the result.
  5.   This function does not support nesting of markers.
  6.   */
  7. function returnSubstrings($text, $openingMarker, $closingMarker) {
  8. $openingMarkerLength = strlen($openingMarker);
  9. $closingMarkerLength = strlen($closingMarker);
  10.  
  11. $result = array();
  12. $position = 0;
  13. while (($position = strpos($text, $openingMarker, $position)) !== false) {
  14. $position += $openingMarkerLength;
  15. if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
  16. $result[] = substr($text, $position, $closingMarkerPosition - $position);
  17. $position = $closingMarkerPosition + $closingMarkerLength;
  18. }
  19. }
  20. return $result;
  21. }
  22. $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">http://www.google.co.uk/search?q=php&num=100&hl=en&safe=off&start=200&sa=N</a>"
  23.  
  24. $urls = returnSubstrings($msg,'">','</a>');
  25.  
  26. print_r($urls);
  27.  
  28. // array (
  29. // 0 => 'http://www.google.co.uk/search?q=php&num=100&hl=en&safe=off&start=200&sa=N'
  30. // )
  31. //

URL: http://uk2.php.net/ereg

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.