简体   繁体   中英

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

I retrieve the next values of my size products: 30X50 or 20x20

I want add the "cm" measure if this values contains the character x or X and only numbers.

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

I need a regular expression. I try with this:

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

But not works

Don't use regular expression in such a trivial case. For example you can write your own domain parse function.

/**
 * 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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