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?
strpos can be used to find the last character
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.
$str = preg_replace('/^.*[a-z]\h*/im', "", $str);
strstr() to do this.
$email = '[email protected]'; $domain = strstr($email, '@'); echo $domain;
// prints @example.com
It seems that you are trying to extract the dollar amount. you can do this alternatively. You can use strrchr:
strrchr ( $string, '$' );
$str = "Job number 45752 Subtotal price $937.50"; $regex = "/.*([a-z])[^a-z]+$/i"; preg_match($regex, $str, $matches,PREG_OFFSET_CAPTURE ); echo $matches;
Array (  => Array (  => Job number 45752 Subtotal price $937.50  => 0 )  => Array (  => e  => 30 ) )
<?php $str ="Job number 3333 Subtotal price $937.50 "; $cost = substr($str, strpos($str, "$") + 1); echo '$'.$cost;
I recommend string functions instead of regex, since they’re a lot faster.
I assume you want the price, just find the last space, and continue from there:
$lastSpace = strros($string, ' ')+1; // find the last space echo substr($string, $lastSpace);
If you have a fixed curr:ency (e.g.:
$), you can do the same thing for the currency character
$lastChar = strros($string, '$')+1; // find the last matching char echo substr($string, $lastChar );
$ would give you the price with sign, +1 without. Whichever your prefer.
While several answers have been given already, I want to point out something that none of them touches, I18N. What if the prices are given in different currencies?
Job number 45752 Subtotal price CHF937.50 Job number 7852 Subtotal amount NOK637.50 Job number 42 Subtotal test SEK427.50 Job number 47592 Subtotal sample DKK976.50
Assuming that a currency is denoted with a special non-alphabetic symbol is false for the vast majority of the world’s currencies. By searching for the last space character like Martijn suggest you will not limit the code to be dollar currency only.
Although the example as given above is not a typical and good one because usually there would be a space between the currency code and the amount when using currency codes. And also assuming that the amount comes after the currency indicator is false for many locales, so there is
more into proper i18n-handling than this, but at least start by not writing code that is limited to handle dollars only.