2012-05-08 51 views
0

我使用simple_html_dom管理CMS驅動圖像嵌入頁面的方式。不過,我希望能夠將任何尚未包裹在錨標記中的圖像包裝到新的錨標記中,但我無法弄清楚如何用新標記包裝simple_html_dom元素。PHP simple_html_dom - >用新的錨點標記包裝元素

我迄今爲止代碼:

$content = str_get_html($content); 
if(is_object($content)) 
{ 
    $elements = $content->find('img'); 
    foreach($elements as $element) 
    { 
/* 
GET INFORMATION ABOUT WHAT IMAGE THIS IS - ALL FINE 
*/   
$classStr = $element->class; 
     if(trim(strlen($classStr)) > 0) 
     { 
      $needle = "wp-image-"; 
      $after = substr($classStr, strpos($classStr, $needle) + strlen($needle)); 
      if(strpos($after, " ")) 
      { 
       $imageID = substr($after, 0, strpos($after, " ")); 
      } 
      else 
      { 
       $imageID = $after; 
      } 
/* 
Get new image to link to 
*/ 
$image = tona_get_image_by_id($imageID, "full"); 

/* 
CHECK IF PARENT OF IMAGE IS AN ANCHOR... IF SO CHANGE THE LINK 
*/ 

      $elementParent = $element->parent(); 
      if(isset($elementParent->href)) 
      { 
       $elementParent->href = $image["src"]; 
       $elementParent->class .= " newAnchorClass ";  
      } 
/* 
IF NOT ADD A NEW ANCHOR TAG ** HELP ** 
*/ 

      echo "IMG: " . $imageID . " " . $image["src"] . "<br/>";  
      $element->href = $image["src"]; 
     } 
    } 
} 

在此先感謝您的幫助。

+0

實際的問題是什麼?你的代碼有什麼問題? – Leri

+0

嗨PLB - 我無法弄清楚如何用新的錨點包裹我的圖像(包含在$元素中)。這樣變成 Tomtids

回答

1

documentation「提示」選項卡下:
$e->outertext = '<div class="wrap">' . $e->outertext . '<div>'

如果您想進一步處理這個元素,就可以使用臨時變量來重新創建DOM。在你的情況下,它會是:

// '$element' is the element to be wrapped 
$tempHtml = str_get_html('<a>' . $element->outertext . '</a>'); 
$link = $tempHtml->find('a', 0); 
// '$src' is the url of the link 
$link->href = $image['src'];