To find and format all prices in a string with PHP, you can use regular expressions to match patterns that look like prices and then format them using the number_format
function.
Here is an example code snippet:
$string = "The price of the product is $9.99 and the shipping cost is $4.50."; // Match all patterns that look like prices preg_match_all('/\$\d+(\.\d{2})?/', $string, $matches); // Loop through each match and format the price foreach ($matches[0] as $match) { $price = (float) str_replace('$', '', $match); $formatted_price = number_format($price, 2); $string = str_replace($match, '$'.$formatted_price, $string); } echo $string;
To find and format all prices in a string with PHP, you can use regular expressions to match patterns that look like prices and then format them using the number_format
function.
Here is an example code snippet:
$string = "The price of the product is $9.99 and the shipping cost is $4.50.";
// Match all patterns that look like prices
preg_match_all('/\$\d+(\.\d{2})?/', $string, $matches);
// Loop through each match and format the price
foreach ($matches[0] as $match) {
$price = (float) str_replace('$', '', $match);
$formatted_price = number_format($price, 2);
$string = str_replace($match, '$'.$formatted_price, $string);
}
echo $string;
In this code, we use the preg_match_all
function to find all patterns that look like prices in the $string
variable. The regular expression /\$\d+(\.\d{2})?/
matches any string that starts with a dollar sign ($
) followed by one or more digits (\d+
) and optionally a decimal point followed by exactly two digits ((\.\d{2})?
).
We then loop through each match and format the price using the number_format
function. Finally, we use the str_replace
function to replace the original price in the string with the formatted price.
This code will output: “The price of the product is $9.99 and the shipping cost is $4.50.”