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

问题描述 投票:1回答:1

这是我的代码:

$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>

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

因此,如果它们之间发生任何意外(最好在此之前),则应在</span>标记之前或之后添加<br>标记。

任何想法我该怎么做?


这是预期的结果:

// expected output: <span>this </span><br>is a test
php html
1个回答
1
投票

您可以通过在串联线后添加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
© www.soinside.com 2019 - 2024. All rights reserved.