StudioTime
StudioTime

Reputation: 23959

PHP remove everything before last instance of a character

Is there a way to remove everything before and including the last instance of a certain character?

I have multiple strings which contain >, e.g.

  1. the > cat > sat > on > the > mat

  2. welcome > home

I need the strings to be formatted so they become

  1. mat

  2. home

Upvotes: 15

Views: 13360

Answers (1)

alex
alex

Reputation: 490153

You could use a regular expression...

$str = preg_replace('/^.*>\s*/', '', $str);

CodePad.

...or use explode()...

$tokens = explode('>', $str);
$str = trim(end($tokens));

CodePad.

...or substr()...

$str = trim(substr($str, strrpos($str, '>') + 1));

CodePad.

There are probably many other ways to do it. Keep in mind my examples trim the resulting string. You can always edit my example code if that is not a requirement.

Upvotes: 35

Related Questions