仅当第二个零件带有特定字符时才拆分零件



我有如下示例所示的字符串集;

"Some string without integer 12345a1% rest of the string with/without integer"

从实际字符串中提取12345a1%后,我想将提取的字符串一分为二;第一部分是数字部分,第二部分是第一个字符和其余数字。但是,只有在起始字符是特定字符(a,d,m,n,o(的情况下,才应该拆分第二部分。

示例;

// First
"Some string 12345a1% some other string."
// Second
"Somet string 23456b2! some other string

期望输出;

// First
0 => 12345
1 => "a1"
// Second
0 => 23456
1 => null

我尝试了以下方法,但结果不正确。

$split = preg_split('/$([0-9]*)(a|d|m|n|os)(d*)/', $input, -1, PREG_SPLIT_NO_EMPTY);

我有什么遗漏吗?提前谢谢。

考虑没有整数部分的某些字符串,您可以从第一位数字开始匹配,然后可以选择匹配后面跟有1位或多位数字的任何[admno]

只有当capture 2值存在而不是null时,它才会为您提供该值。

^[^drn]*b(d+)([admno]d+)?

解释

  • ^字符串开始
  • [^drn]*可选地匹配除换行符或数字之外的任何字符
  • b防止部分字匹配的字边界
  • (d+)捕获组1,匹配1+个数字
  • ([admno]d+)?可选捕获组2,匹配[admno]和1+数字之一

查看regex演示和PHP演示。

例如,使用preg_match而不是preg_split(其中第一个条目是完全匹配(:

$pattern = '/^[^drn]*b(d+)([admno]d+)?/';
$strings = [
"Some string 12345a1% some other string.",
"Somet string 23456b2! some other string"
];
foreach ($strings as $s) {
preg_match($pattern, $s, $match);
var_dump($match);
}

输出

array(3) {
[0]=>
string(19) "Some string 12345a1"
[1]=>
string(5) "12345"
[2]=>
string(2) "a1"
}
array(2) {
[0]=>
string(18) "Somet string 23456"
[1]=>
string(5) "23456"
}

最新更新