如何从PHP中的单个单词字符串中拆分数据?

How to split data from a single word string in PHP?

我需要像下面这样从单个单词字符串中拆分数据,

$string = "RC9999999999A202";

//Need to split as follows:  

$code = "RC"; //This value must be of 2 alphabetic characters
$phone = "9999999999"; //This value must be of 10 digits
$amount = "202"; //This value can be of any length (numeric only)  

我什么都没试过,因为我是新手,对此一无所知。

请帮忙!

请不要留下负面评价,而是尝试帮助我。

如果你的字符串总是像你描述的那样 2 个字符然后 10 数字后跟任意数量的字符那么你可以得到什么你只想像这样使用 substr :

$string = "RC9999999999A202";

echo $code = substr($string, 0, 2); // get first 2 chars
echo $phone = substr($string, 2, 10); // get 10 chars starting from 3d char
echo $amount = substr($string, 12); // get whatever chars left

注意:此方法不验证任何数据,它只是根据您在问题。

您可以将此正则表达式用于 preg_match:

$str = 'RC9999999999A202';

if (preg_match('/([A-Z]{2})(\d{10})\D*(\d*)/', $str, $m)) {
   unset($m[0]); // delete full match from array
   print_r($m);
}

输出:

Array
(
    [1] => RC
    [2] => 9999999999
    [3] => 202
)

RegEx Demo

这将根据您的规格进行匹配并填充变量代码、phone 和金额。

$string = "RC9999999999A202";

Preg_match("/([A-Z]{2})(\d{10})A(\d+)/", $string, $match);

List($string, $code, $phone, $amount) = $match;

https://3v4l.org/QXVRA

此模式假定 "A" 始终是 "A"。
您根本没有在问题中提及它,所以我认为它始终是 "A".