Php 使用不同的分隔符拆分字符串

Php 使用不同的分隔符拆分字符串,php,split,Php,Split,如何将$string拆分为此模式?-->DT-2099-T2(2-4-2) (编辑)-抱歉我的解释不是很有用。 我要做的是将$string中的任何值除以2-4-2,因为我需要验证要匹配的前2个字符/(PP | P1 | DT)/,然后每年验证下4个字符(在本例中是2099(当然这是错误的),但即使是1998年,我也需要验证)和要匹配的最后2个字符/(T1 | T2 | T3)/ 我确实分解了字符串并分配了2-$first、4-$second和2-$third。所以我可以根据。。。但这样验证的一年

如何将
$string
拆分为此模式?--><代码>DT-2099-T2(2-4-2)

(编辑)-抱歉我的解释不是很有用。 我要做的是将$string中的任何值除以2-4-2,因为我需要验证要匹配的前2个字符/(PP | P1 | DT)/,然后每年验证下4个字符(在本例中是2099(当然这是错误的),但即使是1998年,我也需要验证)和要匹配的最后2个字符/(T1 | T2 | T3)/

我确实分解了字符串并分配了2-$first、4-$second和2-$third。所以我可以根据。。。但这样验证的一年不是很开心

所以我假设我可以拆分,然后将年份的4个字符分配给一个变量,并说年份必须是4位数字,介于1100和当前年份之间

我希望这能澄清一点。
谢谢。

您可以为此使用正则表达式,如下例所示。 输出
字符串(10)“DT-2099-T2”

谢谢@El_Vanja

最后,我使用substr对$header执行操作,并为它们分配一个变量,然后独立验证

<?php

$string = 'DT2099T2';

/*
1st Capturing Group (.{2})
.{2} matches any character (except for line terminators)
{2} Quantifier — Matches exactly 2 times
2nd Capturing Group (.{4})
.{4} matches any character (except for line terminators)
{4} Quantifier — Matches exactly 4 times
3rd Capturing Group (.{2})
.{2} matches any character (except for line terminators)
{2} Quantifier — Matches exactly 2 times
*/
preg_match('/(.{2})(.{4})(.{2})/', $string, $matches);

// Skip $matches[0] which contains the text that matched the full pattern.
// Use implode() to glue all parts together, using a hyphen as the separator.
var_dump(implode('-', array_slice($matches, 1)));
$moduleCode=substr($header[0],0,2);
$year=substr($header[0],2,4);
$term=substr($header[0],6,7);
如果((预匹配(/(PP | P1 | DT)/i“,$moduleCode))&($year>1100&$year<2100)和(&(预匹配(/(T1 | T2 | T3)/i“,$term))){
echo“模块代码:”.$header[0]。“
”; }
如果始终是2-4-2,您可以利用它。您不太喜欢正则表达式,因为它不太容易阅读,而且通常需要一些文档,而不是自我文档,而是很好的两行解决方案
<?php

$string = 'DT2099T2';

/*
1st Capturing Group (.{2})
.{2} matches any character (except for line terminators)
{2} Quantifier — Matches exactly 2 times
2nd Capturing Group (.{4})
.{4} matches any character (except for line terminators)
{4} Quantifier — Matches exactly 4 times
3rd Capturing Group (.{2})
.{2} matches any character (except for line terminators)
{2} Quantifier — Matches exactly 2 times
*/
preg_match('/(.{2})(.{4})(.{2})/', $string, $matches);

// Skip $matches[0] which contains the text that matched the full pattern.
// Use implode() to glue all parts together, using a hyphen as the separator.
var_dump(implode('-', array_slice($matches, 1)));
$moduleCode = substr($header[0], 0, 2);
$year = substr($header[0], 2, 4);
$term = substr($header[0], 6, 7);

if((preg_match("/(PP|P1|DT)/i", $moduleCode)) && ($year >1100 && $year < 2100) && (preg_match("/(T1|T2|T3)/i", $term))) {
    echo "Module Code: " . $header[0] . "</br>";
}