PHP regular expression filters html tag attributes (DEMO) and regular expression demo. PHP regular expression filters html tag attributes (DEMO). Regular expression demo filters html tags. there can be built-in functions in php, but the filter is too clean, we have sorted out some useful PHP regular expressions for filtering html tag attributes (DEMO) and regular expressions for 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:
The 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:
The 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:
The code is as follows:
$ Str = preg_replace ("/<([a-z] +) [^>] *>/I", "", $ str );
Filter only the regular expression of the alt attribute:
The code is as follows:
(\ S) alt = [^ \ s] *
Regular expressions used to filter attributes of all html tags:
The code is as follows:
$ Search = array ("' ] *?>. *? 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 );
Regular (DEMO), regular expression demo filter html tags can have built-in functions in php, but it is too clean to filter, we sorted out some benefits...