截断 PHP 中的 UTF8 字词

truncate UTF8 words in PHP

我正在使用此代码将句子分成前 3 个单词,但它不适用于 utf8 字符。

function truncateWords($input, $numwords, $padding="")
{
   $output = strtok($input, " \n");
   while(--$numwords > 0) $output .= " " . strtok(" \n");
   if($output != $input) $output .= $padding;
   return $output;
}

我需要一些帮助来让它也切割 utf8 字符。

例如:"I need some help to make it cut" >> "I need some"

但不适用于 utf8 "Thách Thức Danh Hài 4" 我期待像 "Thách Thức Danh"

这样的结果

您不需要循环来执行此操作,只需使用 explode, array_slice and implode

<?php
$str = 'Thách Thức Danh Hài 4';

//Thách Thức Danh
echo implode(' ', array_slice(explode(' ', $str), 0, 3));

https://3v4l.org/6be5S