我正在撰寫一個 PHP 檔案,它獲取網頁的內容,過濾全角數字,并將它們轉換為半角。目前,我的程式回傳頁面上的所有全角字符,而不僅僅是數字。
<?php
$fullwidthPattern = '/([0-9])/';
$handle = curl_init();
$url = (URL removed for privacy reasons);
function getFullWidth(string $input) {
global $fullwidthPattern;
return preg_match($fullwidthPattern, $input);
}
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($handle);
curl_close($handle);
function jp_str_split($str) {
$pattern = '/(?<!^)(?!$)/u';
return preg_split($pattern,$str);
}
$jpContents = jp_str_split($output);
$numbers = array_filter($jpContents, 'getFullWidth');
foreach($numbers as $x) {
echo $x;
}
我的正則運算式目前是'/([0-9])/',但我也嘗試過'/[0-9]/'和'/[0123456789]/'。
uj5u.com熱心網友回復:
拆分應該與
function jp_str_split($str) {
preg_match_all('/\X/u', $str, $matches);
return $matches[0];
}
該構造完全\X匹配任何 Unicode 字形,您的正則運算式匹配字串內的任何位置,即使在位元組之間,無論標志是否存在(它會影響您使用的字符,而不是匹配字串內的位置)。(?<!^)(?!$)u
此外,由于您處理 Unicode 數字,您還必須u在第二個正則運算式中傳遞標志:
$fullwidthPattern = '/([0-9])/u';
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/533060.html
標籤:php正则表达式卷曲
