Can you pick out the first 1, 2 or 3 digits from 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
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Can you pick out the first 1, 2 or 3 digits from a string?

Post by simonmlewis »

We have URLs a bit like this:

http://www.site.co.uk/product/531/Test- ... /126/LARGE

I want to pick out just that THIRD set of digits (the product ID).
I cannot do it by saying "start at character x and pick up the next 3", because it obviously varies.

Can you think of a way I could collect them into a variable??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Can you pick out the first 1, 2 or 3 digits from a strin

Post by Celauran »

User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can you pick out the first 1, 2 or 3 digits from a strin

Post by requinix »

You can also take the less fun way of explode()ing on slashes and grabbing the 6th (without "http://") or 8th (with) element returned.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Can you pick out the first 1, 2 or 3 digits from a strin

Post by pickle »

Should be able to do it with preg_match(), don't need preg_match_all()
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Can you pick out the first 1, 2 or 3 digits from a strin

Post by simonmlewis »

I think the explode way made work, if you can count how many slashes.
How would that work, given my URL example?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Can you pick out the first 1, 2 or 3 digits from a strin

Post by simonmlewis »

Ahhh I've got it. Very very clever indeed.

Many thanks - Explode() works best.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply