【发布时间】:2015-10-02 11:56:57
【问题描述】:
发现非 UTF 8 字符时 PHP 正则表达式失败!
我需要剥离 40,000 条数据库记录以从 custom_size mysql 表字段中获取宽度和高度值。
文件有各种不同的随机格式。
最可靠的方法是从x 的左侧和右侧获取一个数值,并从中去除所有非数值。
在找到一些非 UTF 8 字符的记录之前,下面的代码在 99% 的情况下都能正常工作。
31*32 和 35”x21” 是 2 个示例。
当这些运行时,我得到这些 PHP 错误和脚本停止......
Warning: preg_replace(): Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 1683977065 on line 21
Warning: preg_match(): Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 0 on line 24
演示:
<?php
$strings = array(
'12x12',
'172.61 cm x 28.46 cm',
'31"x21"',
'1"x1"',
'31*32',
'35”x21”'
);
foreach($strings as $string){
if($string != ''){
$string = str_replace('”','"',$string);
// Strip out all characters except for numbers, letter x, and decimal points
$string = preg_replace( '/([^0-9x\.])/ui', '', strtolower( $string ) );
// Find anything that fits the number X number format
preg_match( '/([0-9]+(\.[0-9]+)?)x([0-9]+(\.[0-9]+)?)/ui', $string, $values );
echo 'Original value: ' .$string.'<br>';
echo 'Width: ' .$values[1].'<br>';
echo 'Height: ' .$values[3].'<br><hr><br>';
}
}
对此有什么想法吗?我无法重建服务器软件以添加支持
刚刚找到了一个可以转换为 UTF8 的 PHP 库的答案,这似乎很有帮助 https://stackoverflow.com/a/3521396/143030
【问题讨论】:
-
如果您的输入不是 utf-8,为什么要使用
u标志?而且该模式似乎不需要它。 -
@Jonny5:如果输入的是 Unicode 文本,
u标志是必须的,因为它会影响模式的解释方式。 -
相关:stackoverflow.com/questions/10037336/… 顺便说一句,如果您发现其他问题解决了您的问题,您可以将您的问题作为重复项关闭,或者将其作为答案发布,而不是将解决方案编辑到问题。
-
@nhahtdh 他只匹配 ascii 字符
0-9、x和文字.没有区别。对于其他情况,我同意你的看法。此外,他正在使用strtolower函数,该函数不是为 utf-8 输入设计的 > 指向输入不是多字节的,否则将使用mb_strtolower。