PHP - Regex to check if <iframe> comes from

2019-08-06 09:03发布

问题:

I'm trying to validate input from user such as this (yes, the <iframe> is the input):

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d7098.94326104394!2d78.0430654485247!3d27.172909818538997!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2s!4v1385710909804" width="600" height="450" frameborder="0" style="border:0"></iframe>

I'm using this regex to check if the input is really an iframe AND comes from google map like this (in php):

if (!preg_match('/<iframe[^>]*src="https:\/\/w.google.com\/maps\/[^"]+">\s*<\/iframe>/', $input)) {
            return \Response::json(array(
                'type'      => 'danger',
                'message' => 'Embedded map should be in iframe tags!',
            ));
        }

This does not work, it never matches all the time (like the input from above). Can someone points me what I'm doing wrong? Thanks.

回答1:

The problem appears to be from this part of your regex

[^"]+">

This is saying anything up until " then preceeded by ">

But in your example it has

sen!2s!4v1385710909804" width="600"

Which wont match

Also you need to escape the . as this means any character and you missed the three www in your regex.



回答2:

I used this regex:

<iframe\s*src="https:\/\/www\.google\.com\/maps\/embed\?[^"]+"*\s*[^>]+>*<\/iframe>

And it is working as expected. Hope that helps.



标签: php regex iframe