I needed a way of automatically generating links from blog posts, based on a pre-defined set of variables, so I built this basic PHP Class. I did’nt’ Google around to see what others had done as I fancied the challenge. I’m sure this can be improved immensely. 🙂
/**
* Link Builder from array
*
* Takes received string and array of text and auto generates links based on the array.
*
* Usage:
* $linkArray[] = array(
* 'link' => 'http://www.kieronhoward.co.uk',
* 'text' => array(
* 'My Website',
* 'kieron howard'
* )
* );
*
* @author Kieron Howard
* @version 1.0
*
*/
Class LinkBuilder
{
private $linkArray;
public function getLinkArray()
{
return $this->linkArray;
}
public function setLinkArray(array $linkArray)
{
$this->linkArray = $linkArray;
return $this;
}
public function addLinkText($link , $text = array())
{
$linkArray = $this->linkArray;
$linkArray[] = array(
'link' => $link,
'text' => $text
);
$this->linkArray = $linkArray;
return $this;
}
public function generateLinks($string)
{
$LinkedText = '';
foreach ($this->linkArray as $linkText)
{
foreach($linkText['text'] as $text)
{
$pattern = '~' . $text . '~';
if(preg_match($pattern, $string, $url))
{
$LinkedText .= preg_replace($pattern, ''.$url[0].'', $string);
}
}
}
if($LinkedText != '')
{
return $LinkedText;
}
else
{
return $string;
}
}
}
Usage:
You can either pass in a predefined array , or use the addLinkText() method.
$linkArray[] = array(
'link' => 'http://www.kieronhoward.co.uk',
'text' => array(
'Kieron Howard',
'my site'
)
);
$LinkBuilder = new LinkBuilder();
$LinkBuilder->setLinkArray($linkArray);
$LinkBuilder->;addLinkText('myLink' , array('MyText' , 'MyText2'));
//will output 'Welcome to my site
echo $LinkBuilder->generateLinks(Welcome to my site);
Recent Comments