在<span> </span>中包装未包装的文本

时间:2012-04-10 03:17:18

标签: php regex

示例:

<div>foo</div>
<p>bar</p>
Unwrapped text

我想要的是什么:

<div>foo</div>
<p>bar</p>
<span>Unwrapped text</span>

如何实现不依赖依赖新行?

2 个答案:

答案 0 :(得分:2)

我不会为html使用正则表达式。

您可以使用phpQuery

执行此操作
$doc = phpQuery::newDocument($html);
$doc->contents()->not($doc->children())->wrap("<span>");
$html = $doc->html();

虽然没试过。

答案 1 :(得分:1)

从您的字符串中提取令牌,例如:<div>foo</div><p>bar</p>,{{ 1}}。您可以使用正则表达式执行此操作。然后

Unwrapped text

这适用于任意嵌套的for each token do if token is opening tag push token on stack else if token is closing tag (and matching opening tag is ontop of stack) pop token from stack else if token is text and stack is not empty ignore token (continue) else if token is text and stack is empty wrap token with <span> - 字符串。

相关问题