-2

I'm trying to grab a word(s) between the word "in" and "with" inside of a string. The problem is that I have another instance of "with", it will extend the wildcard.

Here is an example:

$item   = 'This is a car in red with new tires and with a radio';
$pattern =  = '/in (.*) with/i';
preg_match($pattern, $item, $matches);

Returns:

array(2) {
  [0]=>
  string(30) "in red with new tires and with"
  [1]=>
  string(22) "red with new tires and"
}

What I would like $matches[1] to be is 'red'

hanji
  • 315
  • 2
  • 20

1 Answers1

0

Change your pattern to:

$pattern  = '/in ([^\s]*)(.*) with/i';
// Array ( [0] => in red with new tires and with [1] => red [2] => with new tires and ) 

Where ([^\s]*) means - take all symbols which are not space.

u_mulder
  • 54,101
  • 5
  • 48
  • 64