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'?
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; PHP:
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; Code (markup): would output "eggs and bacon"
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]; PHP: