Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove everything before the first specific character in a string?

My variables look like this:

AAAAAAA, BB CCCCCCCC

AAAA,BBBBBB CCCCCC

I would like to remove everything before the ",",

so the results should look like:

BB CCCCCCCC

BBBBBB CCCCCC

I have worked out this to remove everything AFTER the ",":

list($xxx) = explode(',', $yyyyy);

unfortunately I dont know how to get it to work to remove everything BEFORE the ",".

like image 634
Andrej Avatar asked Mar 16 '11 18:03

Andrej


People also ask

How do I remove all text before after a specific character?

Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).

How do I delete all characters before and after a specific character in Python?

lstrip() #strips everything before and including the character or set of characters you say. If left blank, deletes whitespace.. rstrip() #strips everything out from the end up to and including the character or set of characters you give. If left blank, deletes whitespace at the end.

How do you remove all characters before a certain character from a string in Java?

trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).


2 Answers

Since this is a simple string manipulation, you can use the following to remove all characters before the first comma:

$string = preg_replace('/^[^,]*,\s*/', '', $input);

preg_replace() allows you to replace parts of a string based on a regular expression. Let's take a look at the regular expression.

  • / is the start delimiter
    • ^ is the "start of string" anchor
    • [^,] every character that isn't a comma (^ negates the class here)
      • * repeated zero or more times
    • , regular comma
    • \s any whitespace character
      • * repeated zero or more times
  • / end delimiter
like image 116
Andrew Moore Avatar answered Sep 28 '22 05:09

Andrew Moore


I wouldn't recommend using explode, as it causes more issues if there is more than one comma.

// removes everything before the first ,
$new_str = substr($str, ($pos = strpos($str, ',')) !== false ? $pos + 1 : 0);

Edit:

if(($pos = strpos($str, ',')) !== false)
{
   $new_str = substr($str, $pos + 1);
}
else
{
   $new_str = get_last_word($str);
}
like image 23
Tim Cooper Avatar answered Sep 28 '22 05:09

Tim Cooper