检查字符串是否包含相同的模式


Check if string contains the same pattern

如何检查字符串是否具有这样的特定模式?
XXXX-XXXX-XXXX-XXXX
4个字母数字字符,然后是一个减号,4次类似于上面的结构

我想做的是,我想检查一个字符串是否包含包括"-"在内的结构。

我迷路了,有人能给我指正确的方向吗?

示例代码:

$string = "5E34-4512-ABAX-1E3D";
if ($pattern contains this structure XXXX-XXXX-XXXX-XXXX) {
echo 'The pattern is correct.';
}
else {
echo 'The pattern is invalid.';
}

使用正则表达式

<?php
$subject = "XXXX-XXXX-XXXX-XXXX";
$pattern = '/^[a-zA-Z0-9]{4}'-[a-zA-Z0-9]{4}'-[a-zA-Z0-9]{4}'-[a-zA-Z0-9]{4}$/';
if(preg_match($pattern, $subject) == 1);
    echo 'The pattern is correct.';
} else {
    echo 'The pattern is invalid.';
}
?>

[a-zA-Z0-9]匹配单个字符

{4}与字符完全匹配4次

'-与转义连字符匹配

使用perl正则表达式:

$string = "5E34-4512-ABAX-1E3D";
if (preg_match('/'w{4}-'w{4}-'w{4}-'w{4}/',$string)) {
    echo 'The pattern is correct.';
}

使用preg_match:

$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/', $string)

如果您想考虑小写字符,请使用:

$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/i', $string)