1

我正在尝试使用 php 的preg-match-all函数拆分一些 html 内容:

<li class="cat-item"><a title="blabla" href="#">parent 1</a>
    <ul class="children">
        <li class="cat-item"><a title="" href="#">child 1</a></li>
    </ul>
</li>
<li class="cat-item cat-item-4"><a title="blabla" href="#">father 2</a>
    <ul class="children">
        <li class="cat-item"><a title="" href="#">child 1</a></li>
        <li class="cat-item"><a title="bla" href="#">child 2</a></li>
    </ul>
</li>

例如,我希望能够更改链接描述;

<a title="" href="#">child 1</a>

<a title="" href="#">I changed that</a>

同时保持原始html的结构。到目前为止,我成功地使用以下方法拆分链接:

$results = preg_match_all('/<a\s[^>]*href\s*=\s*(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU', $html, $tokens); 

foreach ( $tokens[0] as $category)
{
    echo $category.'<br>';
}

这样做的缺点是它会丢弃子列表,并输出同一级别的所有列表项;没有父母和孩子的区别。

有什么想法可以保持原有的层次结构吗?

谢谢 :)

4

1 回答 1

0

使用 preg_replace 替换字符串!这里是这样的:

$output = preg_replace("/^([123]0|[012][1-9]|31)(\\.|-|\/|,)(0[1-9]|1[012])(\\.|-|\/)(19[0-9]{2}|2[0-9]{3})$/","$1",$in_nn_date);

其中 $1 或 $2 是您使用正则表达式搜索并分组的内容。

最好是你使用一些在线编辑器或其他东西......就像这个

并在那里尝试!希望能帮助到你...

于 2011-01-27T00:02:18.827 回答