user2650277
user2650277

Reputation: 6739

php regex not working in php [preg_replace}

I am trying to remove the following html but my regex isn't working

<div class="vmargin"><div><iframe src="/test.php?u=N0Bhlant98C6MRj0D44HwJMuf5TdA%2F24oG9hQ2qqX6IR2IruUxVrrhLR4EpHQDvGtuHH4%2BLgJMBG6L5%2BTs6t6FfgCbo%3D&amp;b=5&amp;f=frame" style="width:718px;height:438px;border:0;margin:0;padding:0;" __idm_frm__="100"></iframe></div><div><a href="" class="report_video" data-video-id="732253" title="Report Video">Video Broken?</a></div></div>

I tried the following regex

preg_replace("@<div class=\"vmargin\".*?<\\/div>.*?<\\/div><\\/div>@s",'', $input); 

What's wrong with it

Upvotes: 0

Views: 229

Answers (2)

Rob Baillie
Rob Baillie

Reputation: 3460

I know it's not technically an answer, but to make the result readable (code formatting required)

Works for me:

<?php

$input = '<div class="vmargin"><div><iframe src="/test.php?u=N0Bhlant98C6MRj0D44HwJMuf5TdA%2F24oG9hQ2qqX6IR2IruUxVrrhLR4EpHQDvGtuHH4%2BLgJMBG6L5%2BTs6t6FfgCbo%3D&amp;b=5&amp;f=frame" style="width:718px;height:438px;border:0;margin:0;padding:0;" __idm_frm__="100"></iframe></div><div><a href="" class="report_video" data-video-id="732253" title="Report Video">Video Broken?</a></div></div>';

echo( "!".preg_replace("@<div class=\"vmargin\".*?<\\/div>.*?<\\/div><\\/div>@s",'', $input) .'!' );

Output:

C:\test>php test.php
!!

Moving to ' quoted strings and removing the escaping makes it easier to read though

$input = '<div class="vmargin"><div><iframe src="/test.php?u=N0Bhlant98C6MRj0D44HwJMuf5TdA%2F24oG9hQ2qqX6IR2IruUxVrrhLR4EpHQDvGtuHH4%2BLgJMBG6L5%2BTs6t6FfgCbo%3D&amp;b=5&amp;f=frame" style="width:718px;height:438px;border:0;margin:0;padding:0;" __idm_frm__="100"></iframe></div><div><a href="" class="report_video" data-video-id="732253" title="Report Video">Video Broken?</a></div></div>';

echo( '!'.preg_replace('@<div class="vmargin".*?</div>.*?</div></div>@s','', $input) .'!' );

Same output

Upvotes: 1

vaso123
vaso123

Reputation: 12391

Do not use \\ because in your closing divs, there are no \ character. Try this:

<div class=\"vmargin\".*?<\/div>.*?<\/div><\/div>

So:

$string = '<div class="vmargin"><div><iframe src="/test.php?u=N0Bhlant98C6MRj0D44HwJMuf5TdA%2F24oG9hQ2qqX6IR2IruUxVrrhLR4EpHQDvGtuHH4%2BLgJMBG6L5%2BTs6t6FfgCbo%3D&amp;b=5&amp;f=frame" style="width:718px;height:438px;border:0;margin:0;padding:0;" __idm_frm__="100"></iframe></div><div><a href="" class="report_video" data-video-id="732253" title="Report Video">Video Broken?</a></div></div>';
$input = preg_replace("@<div class=\"vmargin\".*?<\/div>.*?<\/div><\/div>@s", '', $string);
var_dump($input);

Output: string '' (length=0)

Upvotes: 1

Related Questions