我有一个动态内容,其标签很少以" https://"和" http://"。我需要为每个锚标签添加标题,以" https"开头。我使用的代码无法附加动态标题。例如:
$str = '<a href= "https://www.google.com">some text </a>
<a href= "https://www.yahoo.com">some other text </a>';
输出字符串为:
$str = '<a href= "https://www.google.com" title="dynamic title1">some text </a>
<a href= "https://www.yahoo.com" title="dynamic title2">some text </a>'
我使用的代码是:
$xml = '<foo>'. $content.'</foo>';
$doc = new DOMDocument;
$doc->loadXml($xml);
foreach ($doc->getElementsByTagName('a') as $anchor) {
if ($anchor->hasAttribute('title')) {
$anchor->removeAttribute('title');
}
}
$newcontent = $doc->saveHTML();
$pattern = '/(href=("|\')https)(:\\/\\/.*?("|\'))/';
$subject = $newcontent;
preg_match_all ($pattern, $subject, $matches);
for($i=0; $i< count($matches); $i++){
$complete_url = $matches[0][$i];
$get_prog_name = explode("//",$complete_url);
if (strpos($get_prog_name[1],'www.') !== false) {
$get_prog_name = explode("www.",$complete_url);
}
$prog_acro = explode(".", $get_prog_name[1]);
if($prog_acro[0] == "ccc") {
$progName = "Dynamic Title 1";
}
if($prog_acro[0] == "cec") {
$progName = "Dynamic Title 2";
}
$replacement[] = 'class="tooltip" title=Requires CEB '.$progName.'membership login $1$3';
} // end foreach loop
$newstr = preg_replace($pattern, $replacement[0], $subject, -1 );
我想在这里动态替换标题。问题是,当把preg_replace放在循环中时,它会多次打印整个内容,因为它包含一个anhor标签。