'How can I 'cut' a string to a determined length?

I need to receive a long string with lots of characters and 'cut' it to generate a string with the number of characters I determine, how can I do that?

Example:

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

The $text string contains 46 characters in this example.

I need to generate a $newText string with only the 20 first characters, like this:

$newText = 'This is a long strin';


Solution 1:[1]

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

Solution 2:[2]

Not a problem, use substr(). Using your variable names, to get the first 20 characters:

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

This will get a substring of $text, starting at the beginning, stopping after 20 characters.

<edit>Updated to accomodate @rdlowrey suggestion and OP's character set.</edit>

Solution 3:[3]

you mean like this?

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

Solution 4:[4]

Have a look at PHP string functions, and in particular, substr:

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

Returns the portion of string specified by the start and length parameters.

Solution 5:[5]

Check out strlen and substr.

<?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);

?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Taryn
Solution 2 mickmackusa
Solution 3 dldnh
Solution 4 Community
Solution 5 chrisn