I receive an ad and I have to format the French phone number, which must not exceed 10 characters and contain only numbers. In case the criteria are not met I would like to return null.
I am not satisfied with my solution, would you have a simpler solution?
<?php
function formatAds(array $ad): array
{
$ad['last_name'] = ucfirst($ad['last_name']);
$ad['first_name'] = ucfirst($ad['first_name']);
$phoneNumber = str_replace(' ', '', $ad['phone_number']);
$ad['phone_number'] = is_numeric($phoneNumber) && strlen($phoneNumber) === 10 ? $phoneNumber : null;
return $ad;
}
$ad = [
"last_name" => "foo",
"first_name" => "bar",
"phone_number" => "04 55 66 77 11",
];
print_r(formatAds($ad));
You can see the code here: https://3v4l.org/PdTRG
Thanks CBroe , in accordance with what you said, I made these changes with a regex, it seems to work well even with the callsign, if you have other good ideas, I'm still interested.
<?php
function formatAds(array $ad): array
{
$ad['last_name'] = ucfirst($ad['last_name']);
$ad['first_name'] = ucfirst($ad['first_name']);
$phoneNumber = preg_replace(['/ /', '/^0?33/'], ['', '0'], $ad['phone_number']);
$ad['phone_number'] = preg_match('/^0[1-9][\d]{8}$/', $phoneNumber, $matches) ? $matches[0] : null;
return $ad;
}
$ad = [
"last_name" => "foo",
"first_name" => "bar",
"phone_number" => "04 55 66 77 11",
];
$ad2 = [
"last_name" => "flow",
"first_name" => "blow",
"phone_number" => "334 55 66 77 11",
];
$ad3 = [
"last_name" => "beez",
"first_name" => "wiiz",
"phone_number" => "0334 55 66 77 11",
];
print_r(formatAds($ad));
print_r(formatAds($ad2));
print_r(formatAds($ad3));
Output:
Array
(
[last_name] => Foo
[first_name] => Bar
[phone_number] => 0455667711
)
Array
(
[last_name] => Flow
[first_name] => Blow
[phone_number] => 0455667711
)
Array
(
[last_name] => Beez
[first_name] => Wiiz
[phone_number] => 0455667711
)
Code here: https://3v4l.org/PIX3X
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.