PHP Regular Expression filters html tag attributes (DEMO), regular expression demo

Source: Internet
Author: User
Tags php regular expression

PHP Regular Expression filters html tag attributes (DEMO), regular expression demo

Html Tag filtering can have built-in functions in php, but the filtering is too clean. We sorted out some examples of using regular expressions to filter specified html tags, the details are as follows.

When collecting data, you sometimes need to filter out redundant tag attributes. For example, img tags can filter out all attributes except the src attribute, such as deleting titile alt and other attributes, as well as the onclick attribute of some scripts.

For example

Filter all attributes except src:

Copy codeThe Code is as follows:
$ Str = preg_replace ('/\ s (?! Src) [a-zA-Z] + = [\ '\ "] {1} [^ \' \"] + [\ '\ "] {1}/iu ', '$ str );

The above instance code filters out all tag attributes except the src attribute.

Filter settings filter all attributes except alt and src

The Code is as follows:

Copy codeThe Code is as follows:
$ Str = preg_replace ('/\ s (?! (Src | alt) [a-zA-Z] + = [^ \ s] */iu ', '', $ str );

Regular Expressions used to filter attributes of all html tags:

Copy codeThe Code is as follows:
$ Str = preg_replace ("/<([a-z] +) [^>] *>/I", "", $ str );

Filter only the regular expression of the alt attribute:

Copy codeThe Code is as follows:
(\ S) alt = [^ \ s] *

Regular Expressions used to filter attributes of all html tags:

Copy codeThe Code is as follows:
$ Search = array ("'<script [^>] *?>. *? </Script> 'si ", // remove javascript
"'<[\/\!] *? [^ <>] *?> 'Si ", // remove the HTML Tag
"'([\ R \ n]) [\ s] +'", // remove the white space
"'& (Quot | #34);' I", // replaces the HTML Object
"'& (Amp | #38);' I ",
"'& (Lt | #60);' I ",
"'& (Gt | #62);' I ",
"'& (Nbsp | #160);' I"
); // Run as PHP code
$ Replace = array ("", "", "\ 1", "\" "," & "," <","> ","");
$ Html = preg_replace ($ search, $ replace, $ html );

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.