开发者

preg_match with name being last in input

I am trying to get the value from a input field, but the name value is last.

<input value="joe" type="hidden" name="firstname开发者_运维技巧">

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

This is what I am doing, but it's not working.. Anyone know how to fix this?


Once you have your <input …> identified, you can use the following pattern to extract all attributes (taking care of the value delimiters (single quote, double quote, space)).

<?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);

will result in

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

https://gist.github.com/1289335


Try that regex

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

and get the 3rd result


your regex is is fine the last arg of preg_match returns an array

element 0 = entirematch

element 1 = first parenthesis match

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

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


Make sure that your <input> parameters appear in this order in the source. Note that they appear in arbitrary order if you look at them with firebug for example.

Consider replacing hardcoded space '' chars with '\s+' to improve robustness.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜