如何将一根弦切割成一定的长度?

时间:2012-03-23 01:16:53

标签: php string

我需要收到一个包含大量字符的长字符串并“剪切”它以生成一个字符串,其中包含我确定的字符数,我该怎么做?

示例:

$text = 'This is a long string with a lot of characters';

此示例中的$text字符串包含46个字符。

我需要生成一个只有20个第一个字符的$newText字符串,如下所示:

$newText = 'This is a long strin';

5 个答案:

答案 0 :(得分:4)

没问题,请使用substr()。使用变量名称来获取前20个字符:

$newText = mv_substr($text, 0, 20, 'UTF-8');

这将获得$ text的子字符串,从开头开始,在20个字符后停止。

< edit>已更新以容纳@rdlowrey建议和OP的字符集。< / edit>

答案 1 :(得分:3)

你的意思是这样吗?

$newText = substr($text, 0, 20);

答案 2 :(得分:3)

查看PHP string functions,特别是substr

  

string substr( string $string, int $start[, int $length])

     

返回开始长度参数指定的字符串部分。

答案 3 :(得分:2)

结帐strlensubstr

<?php

$text = 'This is a long string with a lot of characters';
echo 'the $text string contains ' . strlen($text) . ' characters in this example.';
$newText = substr($text, 0, 20);

?>

答案 4 :(得分:0)

$newText = mb_substr($text, 0, 20);