gpt4 book ai didi

php - 使用 PHP for MYSQL 获取字符串左右两侧的数字

转载 作者:行者123 更新时间:2023-11-29 02:55:10 25 4
gpt4 key购买 nike

我有一个 MySQL 数据库表列,该列具有多种格式的大小值,用户可以在其中手动输入不同的值格式。

当列值与我们创建的模式匹配时,我需要使用 PHP 迭代数据库表并处理该字段以从每一列中获取一个 withd 和 height 值...

以下是这些格式中 90% 的值。许多格式相同,但在小写字母或大写字母 X

的左侧或右侧有一个或两个数字

Usung PHP 我如何匹配每个字符串以从 X 的左侧和右侧的值中去除所有非数字字符。

左 = 宽度
右侧 = 高度

1x1
1X1
1"x1"

12x12
12X12
12"x12"
12"X12"

NULL
'' ,_ empty field

我只需要将这些值放入 PHP 中的宽度和高度变量中。

如果我可以抓取小写和大写字母 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.";
}

?>

这应该也适用于您添加的额外异常值,因为它首先去除所有非必要字符,然后尝试进行匹配。我还向其中添加了一些显示逻辑,这样您就可以看到原始字符串以及处理后的每个维度,或者如果没有匹配项则显示一条消息。

关于php - 使用 PHP for MYSQL 获取字符串左右两侧的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31395149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com