如何将Simple HTML Dom Parser解析的innertext转为两位小数数值
Got it, let's break this down step by step to get those prices into usable numeric values with two decimal places for your calculations:
Step 1: Extract the raw price values from your innertext
First, we need to pull out the numeric strings from the messy text. A regular expression works perfectly here to target numbers (including those with commas as thousand separators, decimals, or whole numbers).
Step 2: Clean and convert to numeric types
PHP doesn't recognize commas in numeric values, so we'll strip those out, then convert the cleaned string to a float/double that we can perform calculations with.
Step 3: Format to retain two decimal places
After calculations, we can format the result (or individual prices) to ensure they always show two decimal places, even for whole numbers like 0.
Here's a complete example using your input:
// Your raw innertext from simple_html_dom $raw_price_text = "Col price1 1,228.55 Col price2 1228.55 Col price3 0"; // 1. Extract all price values using regex preg_match_all('/(\d{1,3}(?:,\d{3})*\.\d{2}|\d+\.\d{2}|\d+)/', $raw_price_text, $matches); $raw_price_strings = $matches[0]; // Result: ["1,228.55", "1228.55", "0"] // 2. Process each price into a usable numeric value $processed_prices = []; foreach ($raw_price_strings as $price_str) { // Remove thousand separators (commas) $cleaned_str = str_replace(',', '', $price_str); // Convert to float for calculations $numeric_price = (float)$cleaned_str; // Store both the numeric value and formatted string (optional) $processed_prices[] = [ 'value' => $numeric_price, 'formatted' => number_format($numeric_price, 2) ]; } // Example calculation: Sum all prices $total = array_sum(array_column($processed_prices, 'value')); echo "Total: " . number_format($total, 2); // Outputs: Total: 2457.10 // Access individual formatted prices echo "Price 1: " . $processed_prices[0]['formatted']; // Outputs: Price 1: 1228.55 echo "Price 3: " . $processed_prices[2]['formatted']; // Outputs: Price 3: 0.00
Notes:
- If you only need numeric values for calculations (not formatted strings right away), you can skip the
number_formatstep until you're ready to display results. - The regex pattern is flexible enough to handle most common price formats (with/without thousand separators, with/without decimals). If your prices follow a stricter pattern (e.g., always "Col priceX [number]"), you can use a more targeted regex like
/Col price\d+ (\d{1,3}(?:,\d{3})*\.\d{2}|\d+\.\d{2}|\d+)/to directly capture the numeric part.
内容的提问来源于stack exchange,提问作者kiranshiv

