PHP Logo

Lets face it, we’re not the best PHP programmers, or else we’d probably remember how to do this without having to look it up all the time, right? I mean, I’ve looked this one up so many times that I’m actually writing about it in the hopes that I’ll remember next time. Sad!

Luckily this one is really easy and our shame will be over quickly. So here’s the syntax:

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

If you still can’t figure it out, here’s an example:

$result = substr($fullstring, 0, 10);

But if you’re working with strings that could be multi-byte, like unicode strings with special characters, you should probably use mb_substr() instead, which has the same syntax:

$result = mb_substr($fullstring, 0, 10);

You could also use this to get a string out of the middle somewhere by adjusting the start parameter — for example, you could grab the last few characters from the end of the string instead.

Profile Photo for Lowell Heddings Lowell Heddings
Lowell is the founder and CEO of How-To Geek. He’s been running the show since creating the site back in 2006. Over the last decade, Lowell has personally written more than 1000 articles which have been viewed by over 250 million people. Prior to starting How-To Geek, Lowell spent 15 years working in IT doing consulting, cybersecurity, database management, and programming work.
Read Full Bio »