Skip to content

Instantly share code, notes, and snippets.

@callumacrae
Forked from lemon-tree/LinkLocator.php
Created March 11, 2011 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save callumacrae/866732 to your computer and use it in GitHub Desktop.
Save callumacrae/866732 to your computer and use it in GitHub Desktop.
<?php
class URL
{
public function auto($string, $type = 'both', $attr = false, $echo = false)
{
if ($type == 'both' || $type == 'url')
{
$regex = '/(?<anchor><a(?:\s+(?<attr>(?:\S+?=(?:(?:\'.*?\')|(?:".*?")\s*))+))?>(?<text>.*?)<\/a\s*>)|(?<!>)(?<url>(?<proto>https?:\/{2})(?<domain>[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,3})(?<path>\/\S*)?)/i';
return preg_replace_callback($regex, function($matches)
{
if (strlen($matches['anchor']) > 0)
{
if (true) //filter attributes?
{
$attributeString = null;
if (strlen($matches['attr']) > 0)
{
preg_match_all('/' . '(?:\S+?=(?:(?:\'.*?\')|(?:".*?")\s*))' . '/i', $matches['attr'], $attributes);
foreach ($attributes[0] as $attribute)
{
$attibuteSplit = explode('=', $attribute);
if (in_array($attibuteSplit[0], array('href')))
{
$attributeString .= ' ' . $attribute;
}
}
}
}
else
{
$attributeString = ' ' . $matches['attr'];
}
return '<a' . $attributeString . '>' . $matches['text'] . '</a>';
}
else
{
$url = $matches['proto'] . $matches['domain'] . $matches['path'];
return '<a href="' . $url . '">' . $url . '</a>';
}
}, $string);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment