regex将特定的HTML字符串与其中任意数量的空格进行匹配


regex to match a specific HTML string with any number of spaces inside it

我有几行代码,比如这个

<p> &lt;inset&gt;</p>

其中,在打开的<p>标记和字符串的其余部分之间可能有任意数量的空格或制表符(或没有)。我需要更换这些,但我无法让它工作。

我以为这样可以,但它不起作用:

<p>[ 't]+&lt;inset&gt;</p>

试试这个:

$html = preg_replace('#(<p>)'s+(&lt;inset&gt;</p>)#', '$1$2', $html);

如果你想为HTML进行真正的文本修剪,包括你可能遇到的所有东西,比如实体、注释、子元素等等,你可以使用TextRangeTrimmerTextRange:

$htmlFragment = '<p> &lt;inset&gt;</p>';
$dom = new DOMDocument();
$dom->loadHTML($htmlFragment);
$parent = $dom->getElementsByTagName('body')->item(0);
if (!$parent)
{
    throw new Exception('Parent element not found.');
}
$range = new TextRange($parent);
$trimmer = new TextRangeTrimmer($range);
$trimmer->ltrim();
// inner HTML (PHP >= 5.3.6)
foreach($parent->childNodes as $node)
{
    echo $dom->saveHTML($node);
}

输出:

<p>&lt;inset&gt;</p>

我把这两门课都概括为:https://gist.github.com/1894360/(codepad毒蛇倒下了)。

请参阅相关问题/答案:

  • 换行/剪切HTML字符串中的文本
  • 忽略preg_replace中的html标记

尝试将HTML字符串加载到DOM树中,然后trim树中的所有文本值。

http://php.net/domdocument.loadhtml

http://php.net/trim