1mnumb1
1mnumb1

Reputation: 77

Regex to remove iframe with facebook but keeps youtube

I want to remove only iframe(and everyhing inside iframe)with facebook like above but to keep youtube iframe:

<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.example.com%2F%3Fp%313098&amp;layout=standard&amp;show_faces=true&amp;width=500&amp;action=recommend&amp;colorscheme=light" ></iframe>

To keep iframes from youtube:

<iframe width="640" height="360" src="https://www.youtube.com/embed/hiYtWYLEjlI?rel=0" frameborder="0" allowfullscreen></iframe>

I've this regex but it only remove

<\/*i(?:frame|layer)|l(?:ayer|ink)[^>]*+>

https://regex101.com/r/eM9eS3/5

Upvotes: 2

Views: 776

Answers (2)

Jan
Jan

Reputation: 43189

Better take the xpath approach:

$xml = simplexml_load_string($your_html_string);
$iframes = $xml->xpath("//iframe[contains(@src, 'facebook.com')]");

And delete these:

for ($i=0;$i<count($iframes);$i++) {
    $iframe = $iframes[$i];
    unset($iframe[0][0]);
}

Your new XML looks like:

echo $xml->asXML();

As whole function:

function goAwayFacebook($html) {
    $xml = simplexml_load_string($html);
    $iframes = $xml->xpath("//iframe[contains(@src, 'facebook.com')]");
    for ($i=0;$i<count($iframes);$i++) {
        $iframe = $iframes[$i];
        unset($iframe[0][0]);
    }
    return $xml->asXML();
}

$newhtml = goAwayFacebook($html);

Upvotes: 6

user2705585
user2705585

Reputation:

So you are roughly trying to check if www.facebook.com is present in <ifram> or not. This can be achieved by using following regex.

Regex: (?=.*www\.facebook\.com.*)<iframe .*<\/iframe>

Explanation:

  • (?=.*www\.facebook\.com.*) checks for presence of www.facebook.com between the <iframe> tags.

Regex101 Demo

Upvotes: 2

Related Questions