0

i'm using PHP and i want to check the following tags: iframe and script

I want that if they contains X value in the src attribute to add a Y class to the tag and change src attribute name to data-src.

ex.

$blacklist = array("google.com/plus.js", "google.com/drive.js");
$myclass = "blocked";

$html = '<script src="http://google.com/plus.js"></script>';

foreach($blacklist as $black)
{
    $html = preg_replace(...);
}

/* now $html must be: "<script data-src="google.com/plus.js" class="blocked"></script> */

Anyone can help me with this Regex operation?

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • 2
    I would recommend using a combination of [DOMDocument](http://php.net/manual/en/domdocument.loadhtml.php) and [XPath](http://php.net/manual/en/class.domxpath.php) for this and not regex. Also the answers to [this question](http://stackoverflow.com/questions/18349130/how-parse-html-in-php) may help you – segFault Dec 30 '15 at 15:36
  • @sebastianForsberg, i think that 1 regex is fastest than DOMDocument – Vasile Alexandru Peste Dec 30 '15 at 15:39
  • 3
    Well regex can be unreliable for HTML parsing, this depends on your needs and the type of input you are going to be passing to your script(s). See the answer to [this question](http://stackoverflow.com/questions/7067426/load-time-is-it-quicker-to-parse-html-with-phps-domdocument-or-with-regular-ex) for more details... – segFault Dec 30 '15 at 15:42
  • 1
    Also, what have you tried so far? Your code snippet indicates you have not tried any regex patterns yet. If you haven't even attempted a regular expression that is where you should start if that is the route you are going to take. I have used [this tool](https://regex101.com/#pcre) in the past for regex testing. – segFault Dec 30 '15 at 15:46
  • 1
    @VasileAlexandruPeste it doesn't matter if regex are faster if they are incorrect. See http://htmlparsing.com/regexes.html for examples of why this problem is harder than you might originally suspect. Additionally, if you even make a regular expression robust enough to handle all these cases (and more) it very, very quickly becomes unmaintainable. – d0nut Dec 30 '15 at 16:29

1 Answers1

1

I want to help.

To search with regex in the vim. enter image description here

To search with regex in the vim. enter image description here

To substitute with regex in the vim. enter image description here

Mr.kang
  • 587
  • 6
  • 17