繁体   English   中英

PHP:检查我的字符串是否只包含数字和“X”字符

[英]PHP: Check if my string only contains numbers and “X” character

我检索尺寸产品的下一个值:30X50 或 20x20

如果此值包含字符 x 或 X 且仅包含数字,我想添加“cm”度量。

@if($myvalue contains only the character x and numbers)
 {{ $myvalue }} cm // like 20x20cm
@endif

我需要一个正则表达式。 我试试这个:

@if (preg_match('/^\d*(x|X){1}\d*$/',$item->name)) cm.@endif

但不起作用

不要在这种微不足道的情况下使用正则表达式。 例如,您可以编写自己的域解析函数。

/**
 * Parse dimension
 *
 * @return array [dimX, dimY] or empty array when invalid input
 */
function parse(string $meta): array {

    $parseTree = explode('x', strtolower($meta));

    if (2 != \count($parseTree)
            || !ctype_digit($parseTree[0])
                || !ctype_digit($parseTree[1])) {
        return [];
    }

    return $parseTree;

}


/**
 * Test {@see parse}
 * @throws \LogicException When test failed
 */
function testParse() {

    $dataProvider = [
        ['20x50', [20, 50]],
        ['20X50', [20, 50]],
        ['20z50', []],
        ['a20x50', []],
        ['20xa50', []],
    ];


    foreach($dataProvider as $serie) {
        if (parse($serie[0]) != $serie[1]) {
            throw new \LogicException('Test failed');
        }
    }

}


testParse();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM