0

I have an array :

    $testcase = array(
    array('breadjambread', "jam"),
    array('breadjammbread', "jam"),
    array('xxbreadjambreadyy', "jam"),
    array('xxbreadyy', ""),
    array('xxbreadbreadjambreadyy', "breadjamm"),
    array('breadAbread', "A"),
    array('breadbread', ""),
    array('abcbreaz', ""),
    array('xyz', ""),
    array('', ""),
    array('breadbreaxbread', "breax"),
    array('breaxbreadybread', "y"),
    array('breadbreadbreadbread', "breadbread"),
    array('breadbread5breadbread', "breadbread"),
    array('breadbreadbreadbread', "bread5bread"),
);

I want to get the substring between the "bread".

Ex: array[0][0]="breadjambread and I will get the "jam"

    array[1][0]="breadjammbread", I will get the "jamm"

    array[2][0]="xxbreadjambreadyy", the result will be "jam"

Any ideas to solve this?

yassine__
  • 393
  • 4
  • 15
Shin622
  • 645
  • 3
  • 7
  • 22
  • possible duplicate of [Get substring between two strings PHP](http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php) – Rakesh Sharma Sep 08 '14 at 10:07

2 Answers2

0

Use a regular expression:

if (preg_match('/bread(.*?)bread/', $string, $match)) {
    $word_between_bread = $match[1];
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Using a regular expression you can match a string that is surrounded by other strings:

preg_match('/(?<=bread).+?(?=bread)/', $string, $matches);
var_dump($matches);

The .+? is what you are trying to match, (?<=bread) means that it should have "bread" in-front of it and (?=bread) means that it should have "bread" behind it.

You can also use the strpos() and substr() functions to find a string in-between two other strings, but it would require some trial and error on your part.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52