簡體   English   中英

在特定情況下使用正則表達式替換單行中的文本

[英]replace text in single line after specific occurence using regex

我已經在此站點上搜索了問題的解決方案,但是還沒有找到使用正則表達式(或者可能只是縮短了使用較少內存的方法)來完成此任務的方法。 我試圖解析一個字符串,其中要從同一行中刪除特定模式(和模式本身)之后的文本。 模式之前的文本以及任何不包含搜索模式的行均應未經編輯。

這是一個工作示例:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';

$remove = '[test]';
$lines = preg_split('/\r?\n/', $text);
foreach ($lines as $line)
{
    $check = substr($line, 0, stripos($line, $remove));
    $new[] = !empty($check) ? $check . '<br />' : $line;
}

$newText = implode($new);

echo $newText;

上面的代碼按預期工作,但我想知道如何使用正則表達式或使用更少代碼和內存的方法來執行此操作。 我已經嘗試過使用此站點上的示例使用的正則表達式來進行此操作,但需要進行一些修補,但未能獲得所需的結果。 該解決方案還應使用與PHP 5.5語法兼容的代碼(無\\ e修飾符)。 使用數組作為刪除模式也很合適,因為我可能需要搜索多個模式(盡管在我的示例中未顯示)。

謝謝。


感謝frightangel向我展示了正確的正則表達式模式。

以下是完成上述要求的必要代碼:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
[bbc]done.<br />
[another]this line should not be affected.<br />
it works!!<br />';

$removals = array('[test]', '[bbc]');
$remove = str_replace(array('[', ']'), array('~\[', '\].*?(?=\<br\s\/\>|\\n|\\r)~mi'), $removals);  
$text = preg_replace($remove, '', $text);

echo $text;

它搜索的文本實際上來自提供數組的mysql查詢,因此我更改了上面顯示的內容,以使用或多或少會使用的內容($ removals是該數組)。

給我留下的唯一問題是,如果文本是在刪除之前,那么最好從該行保留最后的換行符而不是忽略它。 僅當刪除一行中的所有文本時才應將其省略。

試試這個,然后告訴我您是否要
如果沒有,告訴我,我可能不明白你的問題

 preg_replace("/\[\S+\].+<[^>]+\s?\/>|<[^>]+\s?\/>/m","",$text);

嘗試這種方式:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';

$remove = 'test';

$text = preg_replace("/\[$remove\].*(?=\<br\s\/\>)/m", '', $text);
$text = preg_replace("/^(\<br\s\/\>)|(\\n)|(\\r)$/m","",$text);

echo $text;

這是正則表達式的解釋: http : //regex101.com/r/nW1bG8

暫無
暫無

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

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