求PHP7下替代preg_replace的高效数字变量过滤方案
preg_replace for Extracting Numbers in PHP7 Hey there, let's fix that "A non well formed numeric value encountered" error you're hitting in PHP7. The root issue here is that PHP7 enforces stricter rules when converting non-standard numeric strings (like values with commas, e.g. "1,500") into actual numbers—unlike PHP5, which would quietly truncate or ignore the messy parts. Below are efficient, preg_replace-free solutions for both of your use cases:
1. Keep Only Digits in a String (For $string1)
Option 1: Use filter_var (Fastest Built-in Solution)
PHP's built-in filter_var with FILTER_SANITIZE_NUMBER_INT is purpose-built for this task, and it's way faster than regex:
$string1 = filter_var($string1, FILTER_SANITIZE_NUMBER_INT); // If you want to strip any leading +/-(since the filter keeps them), add this line: $string1 = ltrim($string1, '+-');
This will yank out all non-digit characters (except optional signs) in one go, no regex needed.
Option 2: Character-by-Character Filtering (For Strict Control)
If you want full control over which characters stay, using ctype_digit with array functions is also lightweight:
$string1 = implode('', array_filter(str_split($string1), 'ctype_digit'));
This splits the string into individual characters, keeps only the digits, then glues them back together.
2. Handle Numeric Strings with Commas (For the $price/$special Comparison)
Your original code leaves commas in the string, which is what triggers the PHP7 error—strings like "2,000" aren't considered valid numeric values anymore. Here's how to clean them properly without regex (or with minimal optimized regex):
Option 1: Clean and Convert to Numeric Type
First, let's make a reusable helper function to turn messy strings into proper numbers:
function normalizeNumeric($value) { // Step 1: Remove all characters that aren't digits or commas $cleaned = preg_replace('/[^0-9,]/', '', $value); // Step 2: Strip commas to get a pure numeric string $cleaned = str_replace(',', '', $cleaned); // Step 3: Convert to a float (or int if you're working with whole numbers) return is_numeric($cleaned) ? (float)$cleaned : 0; } // Now rewrite your comparison logic with actual numbers $priceVal = normalizeNumeric($price); $specialVal = normalizeNumeric($special); if ($priceVal < ($specialVal + 2)) { $special = false; }
By converting both values to actual numeric types first, you eliminate the "non-well-formed" error entirely.
Option 2: filter_var + String Replace (Regex-Free)
If you want to ditch regex entirely here too, use filter_var to extract numeric components, then strip commas:
function normalizeNumeric($value) { // Allow numbers, decimals, and signs (adjust flags if you don't need decimals) $cleaned = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // Remove commas $cleaned = str_replace(',', '', $cleaned); return is_numeric($cleaned) ? (float)$cleaned : 0; }
This is even faster than the regex approach because filter_var is optimized at the PHP core level.
Why These Solutions Are Better Than preg_replace
- Speed: Built-in functions like
filter_varandstr_replacerun much faster than regex operations—they're implemented in C, not interpreted like regex patterns. - Reliability: By converting to actual numeric types, you avoid PHP7's strict type warnings entirely.
- Readability: These methods make your intent clearer than regex patterns, which can be hard to parse at a glance.
内容的提问来源于stack exchange,提问作者ilia2

