首页  >  文章  >  后端开发  >  截断字符串时如何保持字边界?

截断字符串时如何保持字边界?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-24 06:32:02922浏览

How to Maintain Word Boundaries When Truncating Strings?

截断字符串时维护单词边界

在之前的查询中,用户试图使用 substr() 将字符串截断为 100 个字符功能。但是,此方法仅获取前 100 个字符,在此过程中可能会破坏单词。

问题陈述

目标是将字符串截断为最多 100 个字符字符,同时确保单词保持完整。例如:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"

$small = truncate_string($big);

echo $small;

// OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"

PHP 解决方案

以下代码提供了解决方案:

<code class="php">function truncate_string($string)
{
    $pos = strpos($string, ' ', 200);
    return substr($string, 0, $pos);
}</code>

说明:

  • strpos() 函数在字符串的前 200 个字符内搜索下一个空格字符。这确保我们不会截断超过前 100 个字符。
  • substr() 函数返回从字符串开头到指定位置的子字符串,即前 200 个字符中第一个空格的位置字符。

以上是截断字符串时如何保持字边界?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn