PHP simple_html_dom - >用新的锚标记包装元素

时间:2012-05-08 09:01:25

标签: php simple-html-dom

我使用simple_html_dom管理CMS驱动图像嵌入页面的方式。但是我希望能够在新的锚标记中包装任何尚未包含在锚标记中的图像,但是我无法弄清楚如何用新标记包装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"];
        }
    }
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分: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'];