Sai*_*Sai 2 php string substring
我有一个电话号码,我想在字符串中添加 2 个空格,我多次使用 substr_replace 来实现此目的。一次使用是否可以实现这一点?
$telephone = "07974621779";
$telephone1 = substr_replace($telephone, " ", 3, 0);
$telephone2 = substr_replace($telephone1, " ", 8, 0);
echo $telephone2; //outputs 079 7462 1779
Run Code Online (Sandbox Code Playgroud)
其中任何一个都可以完成这项工作:
$telephone = "07974621779";
$telephone=substr_replace(substr_replace($telephone," ",3,0)," ",8,0);
// sorry still two function calls, but fewer lines and variables
echo $telephone; //outputs 079 7462 1779
Run Code Online (Sandbox Code Playgroud)
或者
$telephone="07974621779";
$telephone=preg_replace('/(?<=^\d{3})(\d{4})/'," $1 ",$telephone);
// this uses a capture group and is less efficient than the following pattern
echo $telephone; //outputs 079 7462 1779
Run Code Online (Sandbox Code Playgroud)
或者
$telephone="07974621779";
$telephone=preg_replace('/^\d{3}\K\d{4}/',' $0 ',$telephone);
// \K restarts the fullstring match ($0)
echo $telephone; //outputs 079 7462 1779
Run Code Online (Sandbox Code Playgroud)
或者
$telephone = preg_replace('/(?=(?:\d{4}){1,2}$)/', ' ', $telephone);
Run Code Online (Sandbox Code Playgroud)
甚至
$telephone = implode(' ', sscanf($telephone, '%3s%4s%4s'));
Run Code Online (Sandbox Code Playgroud)