【问题标题】:How can I avoid substr() break the html tag?如何避免 substr() 破坏 html 标签?
【发布时间】:2020-02-29 12:31:26
【问题描述】:

这是我的代码:

$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

现在我想避免发生这种情况。我的意思是,&lt;/span&gt; 不能加在&lt;br&gt; 标签的中间。

注意:我保证字符串包含&lt;br&gt;标签。

所以,&lt;/span&gt;标签应该在&lt;br&gt;标签之前或之后添加,如果它们之间有任何意外(最好在此之前)。

知道我该怎么做吗?


这是预期的结果:

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

【问题讨论】:

  • 所以这意味着你想在字符串中添加 标签。
  • 您能否澄清一下:他们之间是否有任何意外
  • @jibsteroos 我的意思是在连接行(第 3 行)中,如果 &lt;span&gt;&lt;br&gt; 之间存在重叠
  • 将标签 span 添加到字符串并使用 str_replace('
    ','
    ',$desc); N.b.这只有在你的字符串中有一个 br 时才有效
  • 如果&lt;br&gt; 接近字符串的末尾,所有前面的单词都应该在范围内吗?每行是否只有 1 个&lt;br&gt;

标签: php html regex


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    相关资源
    最近更新 更多