Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove everything before last instance of a character

Tags:

regex

php

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

like image 727
StudioTime Avatar asked Dec 05 '11 08:12

StudioTime


People also ask

How do I remove all characters before a specific character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.

How do I trim a string after a specific character in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do I remove the first and last character of a string in PHP?

Using trim : trim($dataList, '*'); This will remove all * characters (even if there are more than one!) from the end and the beginning of the string.

How do you delete everything after regex?

Regex Replace We can also call the string replace method with a regex to remove the part of the string after a given character. The /\?. */ regex matches everything from the question to the end of the string. Since we passed in an empty string as the 2nd argument, all of that will be replaced by an empty string.


1 Answers

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.

like image 107
alex Avatar answered Sep 23 '22 18:09

alex