如何在PHP中使用正则表达式删除指定字符串后的特定字符串?

时间:2012-02-09 17:18:14

标签: php regex string

我有一个如下所示的字符串,

 [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

我该怎么做?

3 个答案:

答案 0 :(得分: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 .= "]";

答案 1 :(得分:0)

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

答案 2 :(得分:0)

怎么样:

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

这将删除]pm第一次出现之间]之内的所有字符