Reputation: 1152
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';
Upvotes: 1
Views: 621
Reputation: 26380
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>
Upvotes: 5
Reputation: 56935
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.
Upvotes: 3