I do not know, if I'd understood it right. But I'd written following snippet:
The regex matches some hyperlinks. Then it loops
thru the result and compares the text nodes against the hyperlink references.
When a text node is found in a hyperlink reference, then it extends the matches by inserting a trackback sample link with a unique key.
UPDATE
The snippets finds all hyperlinks:
- find links
- build track back link
- find position of each found link (matches[3]) and
set a template tag
- replace templatetags by trackback links
Each link position is unique.
$string = '<h1>Newsletter Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis,
ligula <a href="http://bar.com">sed sollicitudin</a> dignissim, lacus dolor
suscipit sapien, <a href="http://foo.com">bar.com</a> ipsum ligula
non tortor. Quisque sagittis sodales elit. Mauris dictum blandit lacus.
Mauris consequat <a href="http://last.fm">laoreet lacus</a>.</p>
<h1>Newsletter Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis,
ligula <a href="http://bar.com">sed sollicitudin</a> dignissim, lacus dolor
suscipit sapien, <a href="http://foo.com">bar.com</a> ipsum ligula
non tortor. Quisque sagittis sodales elit. Mauris dictum blandit lacus.
Mauris consequat <a href="http://last.fm">laoreet lacus</a>.</p>
<h1>Newsletter Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis,
ligula <a href="http://bar.com">sed sollicitudin</a> dignissim, lacus dolor
suscipit sapien, <a href="http://foo.com">bar.com</a> ipsum ligula
non tortor. Quisque sagittis sodales elit. Mauris dictum blandit lacus.
Mauris consequat <a href="http://last.fm">laoreet lacus</a>.</p>
';
$regex = '<[^>]+>(.*)<\/[^>]+>';
preg_match_all("'<a\s+href=\"(.*)\"\s*>(.*)<\/[^>]+>'U",$string,$matches);
$uniqueURL = 'http://www.yourdomain.com/trackback.php?id=';
foreach($matches[2] as $k2 => $m2){
foreach($matches[1] as $k1 => $m1){
if(stristr($m1, $m2)){
$uniq = $uniqueURL.md5($matches[0][$k2])."_".rand(1000,9999);
$matches[3][$k1] = $uniq."&refLink=".$m1;
}
}
}
foreach($matches[3] as $key => $val) {
$startAt = strpos($string, $matches[1][$key]);
$endAt= $startAt + strlen($matches[1][$key]);
$strBefore = substr($string,0, $startAt);
$strAfter = substr($string,$endAt);
$string = $strBefore . "@@@$key@@@" .$strAfter;
}
foreach($matches[3] as $key => $val) {
$string = str_replace("@@@$key@@@",$matches[3][$key] ,$string);
}
print "<pre>";
echo $string;