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

标签 php html regex

这是我的代码:

$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>([^>]*)>/

Live Demo


Full code:

$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

关于php - 如何避免 substr() 破坏 html 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689231/

相关文章:

php - 如何在 PHP 中缓存非常动态的网站?

html - 设计第四级菜单项不起作用

java - 计算字符串中的单词数

php - 搜索特定的SQL表,然后在此结果中搜索行

javascript - 如何在不提供绝对路径的情况下流式传输音频文件

javascript - 如何添加 <div></div> 和 name+size+delete 出现在新的 div 中。 javascript jquery

javascript - 传递 AJAX 响应数据字段时,stringify() 意外返回未定义

java - 属性文件中的正则表达式为 False

javascript - 如何编写允许最多 7 个字符加一个空格的正则表达式?

PHP 相当于 [&, epsilon] C++ "Capturing"lambda 变量?