我有一個程式可以從擁有K?或CZK落后于它的鏈中選擇一個數量。如何編輯運算式(模式),以檢查是否K?或CZK在數字前面?參見字串 1 和字串 2:
$string='Rohlík 4,99 K? 51235';
//$string1='Rohlík CZK 4,99 51235';
//$string2='Rohlík K?4,99 51235';
$replace = [' ', '.'];
$string = str_replace($replace,"",$string);
$string = str_replace(',',".",$string);
/*Change?*/
$pattern = '/[0-9]*[.]?[0-9]*[K?,CZK]/';
preg_match($pattern, $string, $matches); // => 4.99 K?
$string = $matches;
$pattern = '/[0-9]*[.]?[0-9]*/';
preg_match($pattern, $string[0], $matches);
$price = $matches[0];
print_r($price); // => 4.99
uj5u.com熱心網友回復:
在您的模式中使用邏輯分組來匹配可能出現在目標數字之前或之后的標簽(在此步驟之后可以用點替換逗號)。
代碼:(演示)
$strings = [
'Rohlík 4,99 K? 51235',
'Rohlík CZK 4,99 51235',
'Rohlík K?4,99 51235',
'Rohlík foo4,99 51235'
];
foreach ($strings as $string) {
var_export(
preg_match('/\b(?:(?:K?|CZK) ?\K\d (?:,\d )?|\d (?:,\d )?(?= ?(?:K?|CZK)))\b/u', $string, $m)
? $m[0]
: 'not found'
);
echo "\n";
}
輸出:
'4,99'
'4,99'
'4,99'
'not found'
模式分解:
/ #starting pattern delimiter
\b #word boundary to guarantee matching the whole label
(?: #start non-capturing group 1
(?:K?|CZK) ? #non-capturing group 2 requiring one of two labels, optionally followed by a space
\K #forget all previously matched characters
\d (?:,\d )? #match the targeted integer/float value with comma as decimal placeholder
| #OR
\d (?:,\d )? #match the targeted integer/float value with comma as decimal placeholder
(?= ?(?:K?|CZK)) #lookahead to for optional space followed by one of the two labels
) #close non-capturing group 1
\b #word boundary to guarantee matching the whole label
/ #ending pattern delimiter
u #unicode/multi-byte flag
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312671.html
上一篇:JS/HTML日期選擇器強制執行規則以確保輸入是今天
下一篇:角度-如何禁用類使用
