Jump to content

Recommended Posts

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'?

Link to comment
https://forums.phpfreaks.com/topic/43798-solved-copy-everything-between-x-and-y/
Share on other sites

<?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');
?>

or something like, should work too for your example, you could modify it to work with another strings, basically as shown above  ;D

 

$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));

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.