Forum Moderators: coopster

Message Too Old, No Replies

How can I get the middle part of a string?

How can I get the middle part of a string?

         

kingdean

4:59 pm on Aug 21, 2006 (gmt 0)

10+ Year Member



Can anyone help me with this problem.

If I have a string such as....

$a = "Start Middle End";

How can I extract "Middle" out of this and put it into $b? I want to do it by searching for the first space and stripping it out of $a. Then I will be left with "Middle End". Then I want to search for the first space and strip it and anything after that and be left with "Middle".

Does anyone know how to easily do this? Can you show me an example of this?

Thanks
Dean

hanglide

5:37 pm on Aug 21, 2006 (gmt 0)

10+ Year Member



If you know that you always want the second word it's easy.

$a = "Start Middle End";
$c = explode(" ", $a);
$b = $c[1];

kingdean

5:50 pm on Aug 21, 2006 (gmt 0)

10+ Year Member



That is helpful but I don't always need the second word. I really need to search for a specific character in the string and strip what came before it including the charactor I searched for (the first time it shows up in the string. Then I have a new string that starts after the charactor and do a search on that new string and do the same thing but after the character.

EX.

$a = "123456@9999$654321";

How can I find "@" in this string and strip it and everything before to be left with this. "9999$654321"? Then I would have something like this I am thinking...

$b = "9999$654321";

Now I want to search this string for "$" and strip it and everything after it to be left with "9999".

Thanks
Dean

coopster

5:25 pm on Aug 22, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



There are a number of ways to accomplish these searches. substr() [php.net] is one way. A combination of substr() [php.net] and strpos() [php.net] is another.
$a = "123456@9999$654321"; 
$b = substr($a, strpos($a, '@') + 1);
print $b; // prints 9999$654321
$c = substr($b, 0, strpos($b, '$'));
print $c; // prints 9999

And regular expressions [php.net] are yet another.
$a = "123456@9999$654321"; 
preg_match [php.net]('/\@([^\$]+)\$/', $a, $matches);
print $matches[1];