在每个字符之间留出空间

时间:2019-09-12 21:12:38

标签: php regex

我希望使用数字和以下字符:+()$phone = '1(54)+45-21'; var_dump(preg_match('/^[\(\)0-9+-]+$/', $phone));

$phone

嗯,效果很好。但我也想在每个字符之间留出空格。因此,+45 (548) - 541 55 11的值可能类似于HTTP/1.1 200 OK Content-Type: application/json Content-Length: 452 { "@odata.context": "https://graph.microsoft.com/beta/$metadata#Collection(microsoft.graph.teamsUserActivityUserDetail)", "value": [ { "reportRefreshDate": "2017-09-01", "userPrincipalName": "userPrincipalName-value", "lastActivityDate": "2017-09-01", "isDeleted": false, "deletedDate": null, "assignedProducts": [ "OFFICE 365 ENTERPRISE E5" ], "teamChatMessageCount": 0, "privateChatMessageCount": 49, "callCount": 2, "meetingCount": 0, "hasOtherAction": true, "reportPeriod": "7" } ] } ,但它也有效,没有任何空格。

如何允许可选空格?

1 个答案:

答案 0 :(得分:1)

试图预测人们可以选择写电话号码的所有荒谬方法,只会削弱您的理智。

$phone = '+1 (234) 567-8900';

// 1. Delete all non-consequential characters.
$phone_bare = preg_replace('/[^\d+]/', '', $phone);

// 2. Check against a simple, sane format.
//      eg: optional +, 11 digits
$result = preg_match('/^\+?\d{11}$/', $phone_bare);

var_dump($phone, $phone_bare, $result);

输出:

string(17) "+1 (234) 567-8900"
string(12) "+12345678900"
int(1)