2011-11-03 39 views
0

我需要瀏覽一個巨大的文件並刪除出現在<>(. .)內的所有字符串。PHP正則表達式來修剪文件

這些括號之間,有可以是任何東西:文本,數字,空格等

如: < there will be some random 123 text here >

我可以讀取該文件,並使用str_replace修剪掉所有的部分,但我不要不知道是如何使用正則表達式來拾取括號內的字符串。

這就是我想做的事:

$line = "this should stay <this should not>"; 
//$trim = do something here using regex so $trim = "<this should not>" 

$line = str_replace($trim,"",$line); 

PS: 數據可能跨線傳播:

this should stay 
(. this 
should 
not .) 

回答

2
$nlstr = "{{{".uniqid()."}}}" 
$str = str_replace("\n",$nlstr,$str); 
$str = preg_replace("/<[^>]*>/","",$str); 
$str = preg_replace("/\(\.([^.)]+[.)]?)*\.\)/","",$str); 
$str = str_replace($nlstr,"\n",$str); 

編輯:編輯通過一個非常hackish的方式,使新行。
編輯:在必要時忘記逃離滿貫和括號。

+0

我不是在正則表達式特別好,但不能簡化你的第一個表達式爲''<.+?> ? – Bojangles

+0

我認爲你必須逃避你的正則表達式中的'('和'.' –

+0

謝謝@SalmanA - 我忘了:) – Benjie

1

如果您不必擔心嵌套(\(\..*?\.\))|(<(.*?>)將做的工作

1

使用非貪婪量詞.*?,以配合最近>一個<。使用s修改把你的字符串中護理換行符:

<?php 
$str = 'this should stay < this should not > 
this should stay (.this should not.) 
this should stay < this 
should 
not > 
this should stay (.this 
should 
not.)'; 
$str = preg_replace('@<.*?>@s', '', $str); 
$str = preg_replace('@\(\..*?\.\)@s', '', $str); 
echo $str; 
?> 

輸出:

this should stay 
this should stay 
this should stay 
this should stay