Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在数字位置将字符串拆分为单词_Php_String - Fatal编程技术网

Php 如何在数字位置将字符串拆分为单词

Php 如何在数字位置将字符串拆分为单词,php,string,Php,String,我有一些字母数字值的字符串数据。如us01name、phc01name和其他,即字母+数字+字母 我想在第一个字符串中获得第一个字母+数字,在第二个字符串中保留 如何在php中执行此操作?您可以使用正则表达式: // if statement checks there's at least one match if(preg_match('/([A-z]+[0-9]+)([A-z]+)/', $string, $matches) > 0){ $firstbit = $matches

我有一些字母数字值的字符串数据。如us01name、phc01name和其他,即字母+数字+字母

我想在第一个字符串中获得第一个字母+数字,在第二个字符串中保留


如何在php中执行此操作?

您可以使用正则表达式:

// if statement checks there's at least one match
if(preg_match('/([A-z]+[0-9]+)([A-z]+)/', $string, $matches) > 0){
    $firstbit = $matches[1];
    $nextbit  = $matches[2];
}
只需将正则表达式分解为多个部分,以便了解每一位的作用:

(              Begin group 1
  [A-z]+         As many alphabet characters as there are (case agnostic)
  [0-9]+         As many numbers as there are
)              End group 1
(              Begin group 2
  [A-z]+         As many alphabet characters as there are (case agnostic)
)              End group 2

可以使用正则表达式:

// if statement checks there's at least one match
if(preg_match('/([A-z]+[0-9]+)([A-z]+)/', $string, $matches) > 0){
    $firstbit = $matches[1];
    $nextbit  = $matches[2];
}
只需将正则表达式分解为多个部分,以便了解每一位的作用:

(              Begin group 1
  [A-z]+         As many alphabet characters as there are (case agnostic)
  [0-9]+         As many numbers as there are
)              End group 1
(              Begin group 2
  [A-z]+         As many alphabet characters as there are (case agnostic)
)              End group 2
请尝试以下代码:

preg_match('~([^\d]+\d+)(.*)~', "us01name", $m);
var_dump($m[1]); // 1st string + number
var_dump($m[2]); // 2nd string
输出 即使这个限制性更强的正则表达式也适用于您:

preg_match('~([A-Z]+\d+)([A-Z]+)~i', "us01name", $m);
请尝试以下代码:

preg_match('~([^\d]+\d+)(.*)~', "us01name", $m);
var_dump($m[1]); // 1st string + number
var_dump($m[2]); // 2nd string
输出 即使这个限制性更强的正则表达式也适用于您:

preg_match('~([A-Z]+\d+)([A-Z]+)~i', "us01name", $m);
您可以在带有模式捕获标志的数字上使用。它会返回所有碎片,所以你必须将它们重新组合在一起。然而,在我看来,它比一个完整的模式regex更直观和灵活。另外,
preg\u split()
使用不足:)

代码:

输出:

Array
(
    [0] => user
    [1] => 01
    [2] => jason
)
您可以在带有模式捕获标志的数字上使用。它会返回所有碎片,所以你必须将它们重新组合在一起。然而,在我看来,它比一个完整的模式regex更直观和灵活。另外,
preg\u split()
使用不足:)

代码:

输出:

Array
(
    [0] => user
    [1] => 01
    [2] => jason
)

thxn。。。更具描述性。。。我使用anubhava toothxn的建议。。。更具描述性。。。我也在使用阿努巴瓦的建议