名称为输入最后的preg_match

时间:2011-10-15 07:34:39

标签: php preg-match

我试图从输入字段中获取值,但名称值是最后一个。

<input value="joe" type="hidden" name="firstname">

preg_match('/input value="(.*?)" type="hidden" name="firstname"/', $request, $firstname);

这就是我正在做的事情,但它不起作用..任何人都知道如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

一旦确定了<input …>,就可以使用以下模式提取所有属性(处理值分隔符(单引号,双引号,空格))。

<?php

$input = '<input value="joe" type="hidden" name="firstname">';
$attributes = array();
$pattern = "/\s+(?<name>[a-z0-9-]+)=(((?<quotes>['\"])(?<value>.*?)\k<quotes>)|(?<value2>[^'\" ]+))/i";
if (preg_match_all($pattern, $input, $matches, PREG_SET_ORDER)) {
  $attributes[$match['name']] = $match['value'] ?: $match['value2'];
}
var_dump($input, $attributes);

将导致

$attributes = array(
    'value' => 'joe',
    'type' => 'hidden',
    'name' => 'firstname',
)

https://gist.github.com/1289335

答案 1 :(得分:0)

试试那个正则表达式

input(.*)?(name=\"(\w+)\")(.*)?

并获得第3个结果

答案 2 :(得分:0)

你的正则表达式很好 preg_match的最后一个arg返回一个数组

元素0 =完整匹配

元素1 =第一个括号匹配

$request = '<input value="joe" type="hidden" name="firstname">';

if (preg_match('/input value="(.*?)" type="hidden" name="firstname"/', $request, $matches)) {
    echo "MATCHED: ", $matches[1];
} 

答案 3 :(得分:0)

确保您的<input>参数在来源中以此顺序显示。请注意,如果您使用firebug查看它们,它们将以任意顺序出现。

考虑将硬编码空间“”字符替换为“\s+”以提高稳健性。