<?php
function captureLink($content)
{
$links = array();
$pattern = "/<a\s+href=[\"\']([^>]+?)[\"\']/iU";
if(preg_match_all($pattern,$content,$matches)) {
for($i = 0;$link = $matches[$i][1];$i++)
array_push($links,$link);
}
return $links;
}
function insertLinksToDb(array $links)
{
$linksDb = array();
foreach($links as $link) {
$hash_link = md5($link);
$sql = "SELECT (id) FROM links WHERE hash LIKE :hash";
$sth = $dbh->prepare($sql);
$sth->bindValue(':hash',$hash_link,PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
$id = $result['id'];
$linksDb[$id] = $link;
} else {
$sql = " INSERT INTO links (hash,link) VALUES(:hash,:link);";
$sth = $dbh->prepare($sql);
$sth->execute(array(':hash'=>$hash_link,':link',$link));
$linksDb[PDO::lastInsertId] = $link;
}
}
return $linksDb;
}
function normallizeLinks($content,array $links)
{
foreach($links as $id => $link) {
//str_replace working faster than strtr
$content = str_replace($link,'/links.php?id='.$id,$content);
}
return $content;
}