簡體   English   中英

php正則表達式無法在php中使用[preg_replace}

[英]php regex not working in php [preg_replace}

我正在嘗試刪除以下html,但是我的正則表達式無法正常工作

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

我嘗試了以下正則表達式

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

它出什么問題了

不要使用\\\\因為在關閉的div中沒有\\字符。 嘗試這個:

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

所以:

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

輸出: string '' (length=0)

我知道從技術上來說這不是一個答案,但是要使結果可讀(需要格式化代碼)

為我工作:

<?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) .'!' );

輸出:

C:\test>php test.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) .'!' );

相同的輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM