Lucas Matos
Lucas Matos

Reputation: 1152

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';

Upvotes: 1

Views: 621

Answers (5)

Surreal Dreams
Surreal Dreams

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

Lucas Matos
Lucas Matos

Reputation: 1152

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

Upvotes: 0

mathematical.coffee
mathematical.coffee

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

dldnh
dldnh

Reputation: 8961

you mean like this?

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

Upvotes: 3

chrisn
chrisn

Reputation: 2135

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

?>

Upvotes: 2

Related Questions