texfield中的数字

问题描述 投票:0回答:1

我有以下文字作为产品名称(示例):“乐高创造者10270 Car V1酷”我只需要提取10270。为此,我有以下php函数:

function my_get_sku( $product_name = "" ) {
     $sku = 0;                       // if no SKU is found, return 0
     $sku_digits = 5;     // change this to the number of digits the SKUs have
     preg_match( '/ [\d]{' . $sku_digits . '} /', $product_name, $match );
     if ( $match ) {
         $sku = trim( $match[0] );
     }     
     return $sku;
}

但我发现,产品文本中的数字可以在4到10位数字之间。我需要提取数字并从numer的开头删除0(如果有的话)。感谢您的帮助

php function trim data-extraction
1个回答
0
投票

这实际上很容易解决,请使用正则表达式\d+来获取具有1个或多个数字的匹配项:

<?php

function my_get_sku($product_name) 
{
    if (empty($product_name))
        return 0;

    preg_match('/\d+/', $product_name, $match);
    if ($match !== false)
        return +$match[0]; // + will remove leading 0

    return 0;
}

echo my_get_sku('Lego creator 010270 Car V1 cool');

返回10270


0
投票

在原始代码中使用$sku_digits的地方,这只是位数(在正则表达式中记为{5})。相反,您需要将其更改为{4,10}以指示所需的字符数。

它还会检查第一位是否为0,并且只删除第一位是否为0。

function my_get_sku( $product_name = "" ) {
    $sku = 0;                       // if no SKU is found, return 0
    preg_match( '/ [\d]{4,10} /', $product_name, $match );
    if ( $match ) {
        $sku = trim( $match[0] );
        if ( $sku[0] == '0' ){
            $sku = substr($sku, 1);
        }
    }
    return $sku;
}

echo my_get_sku("Lego 2 creator 0102704 Car V1 cool");

给出(它会缩短它忽略了前面的2)

102704
© www.soinside.com 2019 - 2024. All rights reserved.