簡體   English   中英

PHP RegEx 刪除特定字符之間的字符

[英]PHP RegEx remove characters between specific characters

我已經做了一些挖掘,似乎無法找到這個問題的確切答案。 我試過在線正則表達式測試器無濟於事。 我正在嘗試從 2 點之間的字符串中刪除文本。

這是字符串的示例:

##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago

我想修剪字符串只說Awesome service

所以,我需要通過sprut刪除##和中間的所有內容,以及Message-ID

我怎樣才能做到這一點?

編輯:為了清楚起見,我試圖將其壓縮到一個 php 表達式中。 這是我所擁有的,但不起作用:

<?php 

if(preg_match('##(.*?)##\\s*(.+?)\\s*Message-Id:.*$',$tweet['tweet'],$matches)) $tweet['tweet'] = $matches[1];
echo (string) trim($tweet["tweet"]);

?>

您可以使用##(.*?)##輕松匹配####之間的部分。 在 message id 之后刪除所有內容也很簡單: Message-Id:.* 連接在一起你有: ~##(.*?)##\\\\s*(.+?)\\\\s*Message-Id:.*$~並且你可以很容易地使用以下之一:

$regex = '~##(.*?)##\\s*(.+?)\\s*Message-Id:.*$~';

// Use replace
$data = preg_replace( $regex, '$2', $data);

// Or match
$matches = array();
if( preg_match($regex, $data, $matches)){
    $data = $matches[2];
}

生活例子在這里

preg_match("!## (.+) Message.+ - (.+)!", $your_text, $taken)

訪問捕獲的單詞,如果它們是 'isset' $taken[1] 和 $taken[2]

您可以使用:

$re = "/##.*?## *| Message-Id:.*$/"; 
$str = "##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago"; 

$result = preg_replace($re, '', $str); // Awesome service

工作演示

您可以使用正向前瞻和后視來提取位於##Message-ID之間的字符串Awesome Service

<?php
$mystring = "##- Please type your reply above this line -## Awesome service Message-Id:5HKR22W0_53adb264b3dc5_63f13f80dc4b33f824958ec_sprut - 3 days ago";
$regex = '~.*(?<=##\s)(.*)(?= Message-Id:).*~';
$replacement = "$1";
echo preg_replace($regex, $replacement, $mystring);
?> //=> Awesome service

工作演示

暫無
暫無

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

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