截断字符串时维护单词边界
在之前的查询中,用户试图使用 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>
说明:
以上是截断字符串时如何保持字边界?的详细内容。更多信息请关注PHP中文网其他相关文章!