SOLVED - How do you cut a string?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
matth2004
Forum Commoner
Posts: 40
Joined: Wed Sep 06, 2006 3:26 am

SOLVED - How do you cut a string?

Post by matth2004 »

Hi,

I was wondering how you would cut a string in PHP to get the first 50 letters of it? Say I have a 200 word variable and I want to get the first 50 letters to the left of it. How would I go about doing so?

Regards,
Matt
Last edited by matth2004 on Sat Feb 17, 2007 6:53 am, edited 1 time in total.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

There's probably a better solution, but one that comes to mind is:

Code: Select all

$newstr = wordwrap($string, 50, '\n', true);
$newstr = explode('\n', $newstr);
$string = $newstr[0];
However, I can see that cutting off the last word of your string completely.

You could also make a loop using strpos() and concatenating each character to a new string until you've hit 50 characters.
matth2004
Forum Commoner
Posts: 40
Joined: Wed Sep 06, 2006 3:26 am

Post by matth2004 »

I just found the substr function where you do:

Code: Select all

$cutstring = substr($var, 0, 50);
Thanks,
Matt
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

That's right. The simple solutions always slip my mind.
Post Reply