preg_match与第一个实例

时间:2016-09-02 16:41:56

标签: php regex

我试图在""之间抓住一个单词。和#34;与"在一个字符串里面。问题是我有另一个""的实例,它将扩展通配符。

以下是一个例子:

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

返回:

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

我希望$ match [1]是' red'

1 个答案:

答案 0 :(得分:0)

将您的模式更改为:

templateUrl

$pattern = '/in ([^\s]*)(.*) with/i'; // Array ( [0] => in red with new tires and with [1] => red [2] => with new tires and ) 的含义 - 取所有不是([^\s]*)的符号。