Kerosene Posted March 22, 2007 Share Posted March 22, 2007 I'm trying to do what I figure is the opposite of preg_replace. 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'? Quote Link to comment https://forums.phpfreaks.com/topic/43798-solved-copy-everything-between-x-and-y/ Share on other sites More sharing options...
skali Posted March 22, 2007 Share Posted March 22, 2007 <?php function get_in_between($haystack,$from, $to){ $str = substr($haystack,strpos($haystack,$from)+strlen($from),strpos($haystack,$to)); $str = substr($str,0,strpos($str,$to)); return $str; } print get_in_between("I am going to the market to buy eggs and bacon for breakfast",'buy','for'); print get_in_between("I am going to the market to buy fruit for breakfast",'buy','for'); ?> Quote Link to comment https://forums.phpfreaks.com/topic/43798-solved-copy-everything-between-x-and-y/#findComment-212657 Share on other sites More sharing options...
mjlogan Posted March 22, 2007 Share Posted March 22, 2007 or something like, should work too for your example, you could modify it to work with another strings, basically as shown above $string = "I am going to the market to buy eggs and bacon for breakfast"; echo substr($string, stripos($string, 'buy')+4, stripos($string, 'for breakfast')-strlen($string)); $string = "I am going to the market to buy fruit for breakfast"; echo substr($string, stripos($string, 'buy')+4, stripos($string, 'for breakfast')-strlen($string)); Quote Link to comment https://forums.phpfreaks.com/topic/43798-solved-copy-everything-between-x-and-y/#findComment-212659 Share on other sites More sharing options...
Kerosene Posted March 22, 2007 Author Share Posted March 22, 2007 Thank you both! I've been wondering about this for months, and previously doing it in such a horrible way (about 30 lines of php!). Quote Link to comment https://forums.phpfreaks.com/topic/43798-solved-copy-everything-between-x-and-y/#findComment-212666 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.