View Full Version : Copy everything between x and y?
Kerosene
Mar 22nd 2007, 2:16 am
I need to copy everything between two constant/known words in a string, e.g
$string = "I am going to the market to buy eggs and bacon for breakfast";
or
$string = "I am going to the market to buy fruit for breakfast";
How can I get 'eggs and bacon', or 'fruit', or whatever else is in between 'buy' and 'for breakfast'?
Houdas
Mar 22nd 2007, 2:36 am
Regular expressions? E.g.
$string = "I am going to the market to buy eggs and bacon for breakfast";
$replace = "fruit";
$string = preg_replace("/(I am going to the market to buy)(.*?)(for breakfast)/is", "\\1 ".$replace." \\3", $string);
echo $string;
Kerosene
Mar 22nd 2007, 2:45 am
Thanks but preg_replace isn't what I'm after. Maybe I didn't explain very well..
I don't want to replace the word, I want to grab it and use it as a variable. So in the above examples, I need to get "eggs and bacon" or "fruit" into a variable.
e.g
$string = "I am going to the market to buy eggs and bacon for breakfast";
???????????????????
echo $market_purchase;
would output "eggs and bacon"
Houdas
Mar 22nd 2007, 4:52 am
OK, then just use preg_match instead of preg_replace:
$string = "I am going to the market to buy eggs and bacon for breakfast";
preg_match("/(I am going to the market to buy)(.*?)(for breakfast)/is", $string, $matches);
echo $matches[2];
Louis11
Mar 22nd 2007, 10:32 am
If you know exactly what you want you could use substr() :)
print substr('abcdef', 0, 4); // abcd
Kerosene
Mar 22nd 2007, 12:51 pm
Thanks guys - I got it working.
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.