我需要接收一个包含大量字符的长字符串,然后将其“剪切”以生成一个具有我确定的字符数的字符串,我该怎么做?
例子:
$text = 'This is a long string with a lot of characters';
Run Code Online (Sandbox Code Playgroud)
$text在此示例中,该字符串包含 46 个字符。
我需要生成一个$newText仅包含前 20 个字符的字符串,如下所示:
$newText = 'This is a long strin';
Run Code Online (Sandbox Code Playgroud)
没问题,使用substr()。使用变量名称获取前 20 个字符:
$newText = mb_substr($text, 0, 20, 'UTF-8');
Run Code Online (Sandbox Code Playgroud)
这将获取 $text 的子字符串,从开头开始,在 20 个字符后停止。
<edit>更新以适应@rdlowrey建议和OP的字符集。</edit>