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