0

i have code like that

<div class="x-ic test"><div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>

i tried a few pattern but i didnt get result i want.

and i need to get result below

<div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>
4

3 回答 3

5

使用DOMDocument- 如果您想再次执行类似操作,我已将代码写入函数:

function DOMinnerHTML(DOMNode $element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $innerHTML .= $element->ownerDocument->saveHTML($child);
    }
    return $innerHTML;
}
function getElContentsByTagClass($html,$tag,$class)
{
    $doc = new DOMDocument();
    $doc->loadHTML($html);//Turn the $html string into a DOM document
    $els = $doc->getElementsByTagName($tag); //Find the elements matching our tag name ("div" in this example)
    foreach($els as $el)
    {
        //for each element, get the class, and if it matches return it's contents
        $classAttr = $el->getAttribute("class");
        if(preg_match('#\b'.$class.'\b#',$classAttr) > 0) return DOMinnerHTML($el);
    }
}

//Calling it:
$html = '<div class="x-ic test"><div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>';

$ret = getElContentsByTagClass($html,'div','x-ic test');//<div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>

PHP 小提琴- 运行 (F9)

于 2013-08-13T09:23:37.620 回答
0

操作 html 的简单且建议的方法是使用 DOM。我个人使用PHP Simple HTML DOM Parser来做到这一点。

但是由于我正在练习正则表达式,所以这里有一个使用正则表达式的答案:):

$text = '<div class="x-ic test"><div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>';

$text = preg_replace('/^(.*)(<div class="abc">.*)(<\/div>)$/', '$2', $text);

// OUTPUT:
<div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div>

你可以试试这里

干杯:)

于 2013-08-13T16:24:04.003 回答
0

要使用正则表达式实现这一点:

<?php 

$html = '<div class="x-ic test"><div class="abc">Test</div><table>.......</table><p>....</p><div style="margin:5px;"></div></div>';

$split = preg_replace('#^<div class="x-ic test">|</div>$#', '' , $html);

var_dump($split);

?>
于 2013-08-13T09:38:34.173 回答