Vir*_*dia 5 php regex string html-parsing
我正在尝试通过令牌拆分HTML字符串,以便创建博客预览而不显示完整的帖子.这比我初想的要难一点.以下是问题:
read_more()可以放在字符串中的任何位置,包括嵌套在段落标记中.可能的用途示例:
<p>Some text here. read_more()</p>
<p>Some text read more() here.</p>
<p>read_more()</p>
<p> read_more()</p>
read_more()
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已尝试在令牌上拆分字符串,但它会留下无效的HTML.正则表达式可能是另一种选择.您将采用什么策略来解决这个问题并使其尽可能防弹?任何代码片段或提示也将受到赞赏(我正在使用PHP).
function stripmore($in)
{
list($p1,$p2) = explode("read_more()",$in,2);
$pass1 = preg_replace("~>[^<>]+<~","><",$p2);
$pass2 = preg_replace("~^[^<>]+~","",$pass1);
$pass3 = null;
while ( $pass3 != $pass2 )
{
if ( $pass3 !== null ) $pass2 = $pass3;
$pass3 = preg_replace("~<([^<>]+)></\\1>~","",$pass2);
}
return $p1."read_more()".$pass3;
}
Run Code Online (Sandbox Code Playgroud)
这会剥离 read_more() 标记之后的所有非 html,并通过剥离相应的标记将其减少到最低限度,同时保持标记之前开始和之后结束的任何标记:
<p>Some text here. read_more()</p>
==> <p>Some text here. read_more()</p>
<p>Some <b>text</b> read_more() <b>here</b>.</p>
==> <p>Some <b>text</b> read_more()</p>
<p>Some <b>text read_more() here</b>.</p>
==> <p>Some <b>text read_more()</b></p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1037 次 |
| 最近记录: |