Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all characters before last alpha character

Tags:

regex

php

I have a mixed string such as:

Job number  45752 Subtotal price $937.50 
Job number  7852 Subtotal amount $637.50 
Job number  42 Subtotal test $427.50 
Job number  47592 Subtotal sample $976.50 

How do I detect the last alphabet character like the 1st sample 'e' on price, and get its position and then remove all other characters in front?

I know strpos can be used to find the last character

strpos(string,find,start)

But how to make it to track any alphabet instead of a fixed one? I am guessing regex might help but just no idea how to put it in. Please help.

like image 871
dan Avatar asked Jul 27 '15 05:07

dan


People also ask

How do I remove all characters before a character in Java?

s1. trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.)

How do I remove all characters from a string after a specific character?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

With regex preg_replace() function, using flags i caseless and m multi-line mode:
To replace from ^ line start to the last alpha with optional spaces, put a greedy dot before [a-z]

$str = preg_replace('/^.*[a-z]\h*/im', "", $str);

\h* matches any amount of horizontal space. See test at regex101, eval.in, regex quickstart

like image 60
Jonny 5 Avatar answered Oct 17 '22 10:10

Jonny 5


I think this can helps:

/.* ([^a-z]+)$/igm

[Regex Demo]
or

/([^a-z]+)$/igm

[Regex Demo]

like image 3
shA.t Avatar answered Oct 17 '22 10:10

shA.t