Ravichandran Jothi
Ravichandran Jothi

Reputation: 3066

How can i remove particular string after the specified string using regex in php?

i have a string like below,

 [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

i need remove the text after the string "pm" upto first occurance of "]".

for example,

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

how can i do this?

Upvotes: 0

Views: 242

Answers (3)

Toto
Toto

Reputation: 91518

How about:

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

This will remove all characters that are not ] between pm and the first occurrence of ]

Upvotes: 0

Sergey Ratnikov
Sergey Ratnikov

Reputation: 1296

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

Upvotes: 0

Nick Rolando
Nick Rolando

Reputation: 26177

If all your strings are in this kind of format, you could use basic string functions

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

Upvotes: 1

Related Questions