How do I return part of 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
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

How do I return part of a string?

Post by impulse() »

I can use

Code: Select all

strstr
to return the part after the needle if found. But I want a function that returns everything before the needle.

EG:

Code: Select all

$string = "autoexec.bat";
echo whatFunction(".", $string);

# outputs autoexec.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

explode()
preg_split()
split()
all come to mind
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

Don't use preg_split() or split() unless you need to use regular expressions to find the needle; explode() will do.

You could also use strpos() and substr() together
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

preg_split and split and explode? What are you guys thinking

Code: Select all

substr($haystack, 0, strpos($haystack, $needle));
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

ole wrote:preg_split and split and explode? What are you guys thinking

Code: Select all

substr($haystack, 0, strpos($haystack, $needle));
Did you read my post?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Oh yeah sorry Aaron.
Post Reply