1

I am working with a string like:

$string = "2017 MODEL YEAR 6.7L POWER STROKE V8 DIESEL 6-SPEED AUTO TRANS 3.55 ELECTRONIC LOCKING AXLE FX4 OFF-ROAD PACKAGE .SKID PLATES 10000-lb. GVWR PACKAGE";

Within the string is the string 10000-lb. GVWR PACKAGE. My goal is to apply number_format to 10000 so that the string reads 10,000-lb. GVWR PACKAGE.

I have been testing with preg_replace and can get to the number using:

preg_replace('!\d+-lb\.!', '\0', $string);

I attempt to apply number_format like:

preg_replace('!\d+-lb\.!', number_format('\0'), $string);

but receive the following error:

number_format() expects parameter 1 to be float, string given

Applying intval() to the match returns a 0 and not the expected 10,000.

I am not sure how to proceed. The catch I have also identified is that I do not want number formatting applied to the first 2017. Do I need to adjust the preg_match to not be as specific or perhaps apply a preg_match to the match within the first preg_match to get the number only?

2
  • Odd that floatval returns the way it does. What kind of variations are there on "10000" can it be "8000"? Commented Sep 12, 2017 at 17:51
  • You can use this answer: Php format numebrs in a string with regexp Commented Sep 12, 2017 at 17:56

1 Answer 1

3

One way to go around it is to match two separate \d's.
First one is one or more digits, second one is exactly three digits.

Then I use str_replace to replace the number in the string.

$string = "2017 MODEL YEAR 6.7L POWER STROKE V8 DIESEL 6-SPEED AUTO TRANS 3.55 ELECTRONIC LOCKING AXLE FX4 OFF-ROAD PACKAGE .SKID PLATES 10000-lb. GVWR PACKAGE";

Preg_match("/(\d+)(\d{3})-lb/", $string, $match);

$find = $match[0];
$replace = $match[1] .",". $match[2] ."-lb";

Echo str_replace($find, $replace, $string);

https://3v4l.org/HvAjg
This will work for numbers 1000+, if you need numbers below 1000 then it needs some tweaks. Just tell me and I will fix it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.