Ravichandran Jothi
Ravichandran Jothi

Reputation: 3066

How do i remove last particular string using regex?

Hi i have the string like below,

$aa = "Ability: N/S,Session: Session #2: Tues June 14th - Fri June 24th (9-2:00PM),Time: 10:30am,cname: karthi";

$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1:30pm,cname: ravi";

$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";

i need to write single regex for removing the particular string from ",cname:" upto last. i need output like,

$aa = "Ability: N/S,Session: Session #2: Tues June 14th - Fri June 24th (9-2:00PM),Time: 10:30am";

    $aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1:30pm";

    $aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am";

how can i do this in regex?

Upvotes: 0

Views: 305

Answers (4)

Toto
Toto

Reputation: 91518

If you have more than one ,cname:... and just want to remove the last one, use this:

$aa= preg_replace('/,cname:.*?$/', '', $aa);

Upvotes: 0

m0skit0
m0skit0

Reputation: 25874

/^(.*),cname:.*;$/

Group 1 ($1) generated by this regex will give you the result you want.

Upvotes: 0

rodneyrehm
rodneyrehm

Reputation: 13557

You don't need regex for this. You can use strpos() to find the index of ',cname:' and then substr() up to that index.

<?php

$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
$pos = strpos($aa, ',cname:');
$bb = substr($aa, 0, $pos);
echo $bb, "\n";

but if you, for whatever reason, insist on using regex for this, you'll want to use preg_replace():

<?php

$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
$bb = preg_replace('#,cname:.*$#', '', $aa);
echo $bb, "\n";

and if you don't want to modify the string, you may want to use preg_match():

<?php

$aa = "Ability: N/S,Session: Session #1: Tues May 31st - Fri June 10th (1-5:30PM),Time: #1 only: 1am,cname: mathi";
if (preg_match('#^(.+),cname:.*$#', $aa, $match)) {
    echo $match[1], "\n";
}

Upvotes: 1

stema
stema

Reputation: 93086

Try

/,cname:.*$/

and replace with an empty string.

$result = preg_replace('/,cname:.*$/', '', $aa);

See it here on Regexr

Upvotes: 1

Related Questions