2011-09-15 39 views
-1

我正在从文本编辑器读取HTML字符串,并且在将其保存到数据库之前需要处理一些元素。PHP从字符串操作HTML

什么我已经是这样的:

<h3>Some Text<img src="somelink.jpg" /></h3> 

<h3><img src="somelink.jpg" />Some Text</h3> 

,我需要把它放到下面的格式

<h3>Some Text</h3><div class="img_wrapper"><img src="somelink.jpg" /></div> 

这是我提出的解决方案。

$html = '<html><body>' . $field["data"][0] . '</body></html>'; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 

$domNodeList = $dom->getElementsByTagName("img"); 

// Remove Img tags from H3 and place it before the H# tag 
foreach ($domNodeList as $domNode) { 
    if ($domNode->parentNode->nodeName == "h3") { 
     $parentNode = $domNode->parentNode; 
     $parentParentNode = $parentNode->parentNode; 

     $parentParentNode->insertBefore($domNode, $parentNode->nextSibling); 
    } 
} 

echo $dom->saveHtml(); 
+3

[所有你需要的是爱] http://php.net/manual/en/book.dom.php – pleasedontbelong

回答

0

我更新的答案的问题,但良好的措施,这里要再次重申的答案部分。

$html = '<html><body>' . $field["data"][0] . '</body></html>'; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 

$domNodeList = $dom->getElementsByTagName("img"); 

// Remove Img tags from H3 and place it before the H# tag 
foreach ($domNodeList as $domNode) { 
    if ($domNode->parentNode->nodeName == "h3") { 
     $parentNode = $domNode->parentNode; 
     $parentParentNode = $parentNode->parentNode; 

     $parentParentNode->insertBefore($domNode, $parentNode->nextSibling); 
    } 
} 

echo $dom->saveHtml(); 
1

你可能会寻找一个的preg_replace

// take a search pattern, wrap the image tag matching parts in a tag 
// and put the start and ending parts before the wrapped image tag. 
// note: this will not match tags that contain > characters within them, 
//  and will only handle a single image tag 
$output = preg_replace(
    '|(<h3>[^<]*)(<img [^>]+>)([^<]*</h3>)|', 
    '$1$3<div class="img_wrapper">$2</div>', 
    $input 
); 
+0

注2:这不会像搬出航向,更好地在这里使用DOM – feeela

+0

糟糕,错过了这部分的问题。谢谢。 – rrehbein