[英]Different patterns but the result is the same
我想获取字符串中的输入值。 我为此使用了两种不同的模式。 但结果是一样的。 这是什么原因?
$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
这是什么原因?
正如@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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.