Example of php regular expression matching a tag

Source: Internet
Author: User
Tags php regular expression

Method 1

The code is as follows: Copy code

$ A = '<a href = "www.111cn.net"> Baidu </a> gu ge <a href = "www.111cn.net"> Google </a> <a href = "www.111cn.net"> Yahoo </a> ';
Preg_match_all ('/<a [^>] +> [^>] + a>/', $ a, $ aout );
Print_r ($ aout );

Result

Array

(

[0] => Array

        (

[0] => <a href = "www.111cn.net"> Baidu </a>

[1] => <a href = "www.111cn.net"> Google </a>

[2] => <a href = "www.111cn.net"> Yahoo </a>

        )

 

)

Method 2

Example:

The code is as follows: Copy code
$ Str1 = '<a href = http://www.111cn.net> test </a> ';
$ Str2 = '<a href = 'http: // www.111cn.net'> test </a> ';
$ Str3 = '<a href = "export cnames: href ('test');" target = "_ blank"/> test </a> ';
$ Regex = '/hrefs * = s *(? : "([^"] *) "| '([^'] *) '| ([^"'> S] + ))/';
Preg_match ($ regex, $ str1, $ matches );
Print_r ($ matches );
Preg_match ($ regex, $ str2, $ matches );
Print_r ($ matches );
Preg_match ($ regex, $ str3, $ matches );
Print_r ($ matches );
 
Matching result:
Array
(
[0] => href = http://www.111cn.net
[1] =>
[2] =>
Http://www.111cn.net
)
Array
(
[0] => href = 'http: // www.111cn.net'
[1] =>
Http://www.111cn.net
)
Array
(
[0] => href = "export cnames: href ('test ');"
[1] => export cnames: href ('test ');
)

/Href \ s * = \ s *(? : "([^"] *) "| \ '([^ \'] *) \ '| ([^" \'> \ S] + ))/
The idea is clever:
In two steps, configure the tag first, and then configure the link in the tag.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.