You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用simple_html_dom解析表格时格式化单元格内容的问题

解决simple_html_dom解析表格后的数字格式化问题

Got it, let's work through this problem step by step. The core issue here is that everything you pull from HTML via simple_html_dom is a string—so checking !is_int() won't work, because even "17" is a string, not an integer type. That's why your previous code was turning integers into decimal values.

Here's a reliable approach to handle each case correctly:

We'll use regular expressions to identify the type of content in each cell (text, integer string, two-decimal float string), then apply the right formatting rule.

// Assume $cell is your simple_html_dom cell object, get its content
$cell_content = trim($cell->plaintext);

$formatted_content = $cell_content; // Default to original text

// Check if it's a pure integer string (no decimal point)
if (preg_match('/^\d+$/', $cell_content)) {
    // Do nothing, keep as is
    $formatted_content = $cell_content;
}
// Check if it's a float with exactly two decimal places
elseif (preg_match('/^\d+\.\d{2}$/', $cell_content)) {
    // Convert to float, round to 1 decimal place
    $float_value = (float)$cell_content;
    $rounded = round($float_value, 1);
    
    // Optional: If rounded value is an integer (e.g., 24.0), convert back to integer string
    if (floor($rounded) === $rounded) {
        $formatted_content = (string)(int)$rounded;
    } else {
        $formatted_content = (string)$rounded;
    }
}
// For text content, we already set the default above, so no action needed

// Use the formatted content as needed
echo $formatted_content;

Why this works:

  • trim() cleans up any extra whitespace that might be hiding in table cells (super common in HTML tables!)
  • The first regex /^\d+$/ matches strings that are only digits (no decimals)—these are your integers.
  • The second regex /^\d+\.\d{2}$/ matches strings that have exactly one decimal point followed by two digits—your target floats.
  • We only round the values that fit the two-decimal float pattern, so integers and text stay untouched.

Example outputs:

  • "abc" → "abc"
  • "17" → "17"
  • "24.24" → "24.2"
  • "24.29" → "24.3"
  • "17.00" → "17" (if you use the optional integer conversion)

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:45:47