Pulling a substring out of the middle 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
mrlab
Forum Newbie
Posts: 1
Joined: Thu Feb 18, 2010 2:52 pm

Pulling a substring out of the middle of a string

Post by mrlab »

hey,
I'm trying to pull a substring out of this string I have created based off of my query...
What I want is to pull the three different variables and set them each to strings.
here's a photo of said string
Image
I can get the first and the last portions by using the following:

$vn = substr($vehicle, 0, strpos($vehicle, '~'));
&
$vp = substr($vehicle, strpos($vehicle, '|'));

but not the middle variable...
any help would be most appreciated
Thanks,
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: Pulling a substring out of the middle of a string

Post by manohoo »

mrlab, please be more specific. For instance, I want string "vehicle_name" to become "name"... or I want to remove "text" from "this_text"...
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Pulling a substring out of the middle of a string

Post by pickle »

So you've got a string like: "Camaro~Sports Car|19995"?

I can think of 2 ways:

1)Convert the ~ to a | & explode

Code: Select all

$string = str_replace('~','|',$string);
list($vn,$vd,$vp) = explode('|',$string);
2) Use regex: /(.*)~(.*)\|(.*)/
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply