模式不同,但结果相同

时间:2019-03-30 09:17:52

标签: php

我想获取字符串中的输入值。我为此使用两种不同的模式。但是结果是一样的。这是什么原因?

$string = 'hello world is .. <input type="text" id="level" value="5">  <input type="text" id="option" value="24"> .. tyhis is example text.';

$pattern = '/<input(?:.*?)id=\"option\"(?:.*)value=\"([^"]+).*>/i';
$pattern2 = '/<input(?:.*?)id=\"level\"(?:.*)value=\"([^"]+).*>/i';

preg_match($pattern, $string, $matches);
preg_match($pattern2, $string, $matches2);
echo $matches[1];
echo "<br>";
echo $matches2[1];

结果:

  

24

     

24

这是什么原因?

1 个答案:

答案 0 :(得分:0)

正如@Andreas已经指出的那样,您的模式包含贪婪的部分,这些部分占用了过多的输入。您需要减少:

<?php
$string = 'hello world is .. <input type="text" id="level" value="5">  <input type="text" id="option" value="24"> .. this is example text.';

$pattern1 = '/<input\s.*\sid=\"option\"\s.*?value=\"([^"]+).*>/i';
$pattern2 = '/<input\s.*\sid=\"level\"\s.*?value=\"([^"]+).*>/i';


preg_match($pattern1, $string, $matches1);
preg_match($pattern2, $string, $matches2);

var_dump($matches1[1], $matches2[1]);

显而易见的输出是:

string(2) "24"
string(1) "5"
相关问题