Copy everything between x and y?

Discussion in 'PHP' started by Kerosene, Mar 22, 2007.

  1. #1
    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'?
     
    Kerosene, Mar 22, 2007 IP
  2. Houdas

    Houdas Well-Known Member

    Messages:
    158
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #2
    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:
     
    Houdas, Mar 22, 2007 IP
  3. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,366
    Likes Received:
    575
    Best Answers:
    4
    Trophy Points:
    385
    #3
    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"
     
    Kerosene, Mar 22, 2007 IP
  4. Houdas

    Houdas Well-Known Member

    Messages:
    158
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #4
    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:
     
    Houdas, Mar 22, 2007 IP
  5. Louis11

    Louis11 Active Member

    Messages:
    783
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    70
    #5
    If you know exactly what you want you could use substr() :)

    print substr('abcdef', 0, 4);  // abcd
    PHP:
     
    Louis11, Mar 22, 2007 IP
  6. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,366
    Likes Received:
    575
    Best Answers:
    4
    Trophy Points:
    385
    #6
    Thanks guys - I got it working.
     
    Kerosene, Mar 22, 2007 IP