在包含<a> tag</a>的整个内容中附加标题标记

时间:2014-04-04 04:21:47

标签: php xml dom preg-replace

我有一个动态内容,其标签很少以&#34; https://&#34;和&#34; http://&#34;。我需要为每个锚标签添加标题,以&#34; https&#34;开头。我使用的代码无法附加动态标题。例如:

$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&nbsp;CEB&nbsp;'.$progName.'membership&nbsp;login $1$3';
 } // end foreach loop
 $newstr =  preg_replace($pattern, $replacement[0], $subject, -1 );

我想在这里动态替换标题。问题是,当把preg_replace放在循环中时,它会多次打印整个内容,因为它包含一个anhor标签。

0 个答案:

没有答案