开发者

Using Regex to get the value in a HTML tag?

开发者 https://www.devze.com 2023-04-12 12:33 出处:网络
I\'m using this regex code to get the tags but not the value: (<input type=\"hidden\" name=\"pt\" id=\"pt\" value=\")|(\" \\/>)

I'm using this regex code to get the tags but not the value:

(<input type="hidden" name="pt" id="pt" value=")|(" \/>)

From this code:

<input type="hidden" name="pt" id="pt" value="f64b1aadf7baa6e416dbfb6bf95fa031" />

But how开发者_高级运维 would I do it the other way around? Get the value, but not the surrounding tags? So I would only get "f64b1aadf7baa6e416dbfb6bf95fa031" (without the quotes). Thanks.


As Donut says, you seriously shouldn't use regexes on HTML. However, since this is a pretty straightforward case I'll be an enabler. But seriously, if it gets one iota more complicated, switch to a DOM parser.

value="(.+?)"

I'm assuming you are using PHP, so to get the captured group out, do this:

preg_match('value="(.+?)"', $input, $groups);
echo "Value = " . $groups[1];

The ? makes it a lazy operator, so it grabs up to the first quotation mark. If there is the possibility of escaped quotation marks inside the quotation marks you need to add this:

value="(.+?[^\\])"


While it is generally not advisable to attempt to parse HTML with regular expressions, you could try this: value="([^"]*)".

0

精彩评论

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

关注公众号