Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten a text string in PHP

Tags:

php

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:

$string = "this is a string";

How could I trim it to say:

$newstring = "this is";

This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?

function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}

I also looked at this question, but I don't really understand it.

like image 921
imulsion Avatar asked Oct 23 '25 23:10

imulsion


1 Answers

if (strlen($yourString) > 15) // if you want...
{
    $maxLength = 14;
    $yourString = substr($yourString, 0, $maxLength);
}

will do the job.

Take a look here.

like image 150
DonCallisto Avatar answered Oct 25 '25 15:10

DonCallisto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!