这是我的代码:
$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
$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/