我有一个MySQL数据库表列,它有多种格式的大小值,用户手动输入不同的值格式。
使用PHP,我需要迭代DB表并处理此字段,以便在列值匹配到我们创建的模式时从每列获取withd和height值…
下面是这些格式中90%的值。许多格式相同,但在小写或大写X
使用PHP如何匹配每个字符串以从x的左侧和右侧的值中剥离所有非数字字符
left = width
右侧= height
1x1
1X1
1"x1"
12x12
12X12
12"x12"
12"X12"
NULL
'' ,_ empty field
我只需要把这些值转换成PHP的宽度和高度变量。
如果我能抓取小写X和大写X左边的所有内容以及右边的所有内容并删除所有非数字那么我认为它会很容易完成
还有其他值,这些值应该被忽略,因为它们不适合模式。下面是我目前发现的一些奇怪值的例子:
18" channel letters
64x20 x 2
Glass Dimensions: 12"x72"
172.61 cm x 28.46 cm
230.15 cm x 42.07 cm
24x24 Interior Double Sided
这些类型的值应该被忽略,所以我可以稍后手动编辑这些
我编写了一个名为rough_strip_all
的函数,它应该删除字符串中除了列出的字符之外的所有字符。添加此步骤可能会为您解决问题,但如果没有,您可能需要重新编译以启用对PCRE的UTF8支持。
<?php
// Strips out all characters except for those in allowed set
function rough_strip_all( $string, $allowed_set = '0123456789x. ' )
{
// Takes the allowed set, splits it into character by character,
// then converts each character in the array to its ASCII value
$allowed_ascii = array_map( function($a) {
return ord( $a );
}, str_split( $allowed_set ) );
$return = '';
for( $i = 0, $ilen = mb_strlen( $string ); $i < $ilen; $i++ )
{
// Check if the ASCII value of current character is in the list of allowed
// ascii characters given. If it is, add it to the return string
$ascii = ord( $string{$i} );
if( in_array( $ascii, $allowed_ascii ) )
{
$return .= $string{$i};
}
}
// Returns the newly compiled string
return $return;
}
// Original string
$string = "Misc text: 35.25”x 21.00” 123 extra text 456";
// Display original string
echo "Original string: {$string}<br />";
// Strips out all characters except the following: '0123456789x. '
$string = rough_strip_all( strtolower( $string ) );
// Strip out all characters except for numbers, letter x, decimal points, and spaces
$string = preg_replace( '/([^0-9x '.])/ui', '', $string );
// Find anything that fits the number X number format (including decimal numbers)
preg_match( '/([0-9]+('.[0-9]+)?) ?x ?([0-9]+('.[0-9]+)?)/ui', $string, $values );
// Match found
if( !empty( $values ) )
{
// Set dimensions in easy to read variables
$dimension_a = $values[1];
$dimension_b = $values[3];
// Values returned
echo "Dimension A: {$dimension_a}<br />";
echo "Dimension B: {$dimension_b}<br />";
}
// No match found
else
{
echo "No match found.";
}
?>
这也应该适用于您添加的其他异常值,因为它首先剥离所有非必要字符,然后尝试进行匹配。我还为它添加了一些显示逻辑,这样您就可以看到原始字符串以及处理后的每个维度是什么,如果没有匹配,则可以看到消息。
preg_match_all("/[0-9]+/", $string, $matches);
1 x11 '"x112 x12数组([0]=>数组([0]=> 1[1]=> 1))数组([0]=>数组([0]=> 1>[1]=> 1))数组([0]=>数组([0]=> 12 [1]=> 12))