[英]PHP simple_html_dom -> wrap an element with a new anchor tag
我正在使用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"];
}
}
}
在此先感謝您的幫助。
在“提示”標簽下的文檔中 :
$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'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.