繁体   English   中英

如何避免 substr() 破坏 html 标签?

[英]How can I avoid substr() break the html tag?

这是我的代码:

$desc = "this <br>is a test";
$maxLen = 7;
$structured_desc = "<span>" . mb_substr($desc, 0, $maxLen) . "</span>" . mb_substr($desc, $maxLen);
echo $structured_desc;

这是上面代码的结果:

// output: <span>this <b</span>r>is a test

现在我想避免发生这种情况。 我的意思是, </span>不能添加到<br>标签的中间。

注意:我保证字符串包含<br>标签。

所以, </span>标签应该加在<br>标签之前或之后,如果它们之间有任何意外的话(最好是在那之前)。

知道我该怎么做吗?


这是预期的结果:

// expected output: <span>this </span><br>is a test

您可以通过在连接行之后添加一个preg_replace()来处理它。 这是模式:

/<([^>]*)<\/span>([^>]*)>/

现场演示


完整代码:

$desc = "this <br>is a test";
$maxLen = 7;
$structured_desc = "<span>" . mb_substr($desc, 0, $maxLen) . "</span>" . mb_substr($desc, $maxLen);
$structured_desc = preg_replace('/<([^>]*)<\/span>([^>]*)>/', '<span><$1$2>', $structured_desc);
echo $structured_desc;

//=> <span>this <span><br>is a test

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM