2012-02-09 65 views
0

我有一個字符串像下面,如何在PHP中使用正則表達式指定字符串後刪除特定的字符串?

[Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV] => 2 
    [Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 2pmADV] => 1 
    [Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 2pmADV] => 1 
    [Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmN/S+] => 1 
    [Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 2pmN/S+] => 1 
    [Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 3:30pmN/S+] => 1 

我需要的字符串「PM」高達的「]」第一次出現後,刪除文本。

例如,

from 
[Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV] => 2 
to 
[Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pm] => 2 

我怎麼能做到這一點?

回答

0
$str = "[Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV] => 2" 
echo preg_replace('/(?<=pm)\S*?(?=])/is', '', $str); 
1

如果您的所有字符串都是這種格式,你可以使用基本字符串函數

$str = "[Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pmADV]"; 
$str = substr($str, 0, strpos($str, "pm") + 2); 
$str .= "]"; 
0

如何:

$str = preg_replace("/(pm)[^\]]+(\])/", "$1$2", $str); 

這將刪除不]所有字符pm與第一次出現]

相關問題