Как заменить все вхождения символа на различные значения не прибегая к циклам?

у меня есть маска для телефона +7(###)###-##-## и приходит телефонный индекс 1234145577 как заменить все вхождения символа # на телефонный индекс без цикла
  • Вопрос задан
  • 171 просмотр
Решения вопроса 1
@dodo512
$str = '1234145577';
$mask = '+7(###)###-##-##';
$i = 0;

$result = preg_replace_callback(
    '/#/',
    function ($m) use ($str, &$i) {
        return $str[$i++] ?? $m[0];
    },
    $mask
);

echo $result;
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
Fernus
@Fernus
Техник - Механик :)
<?php

$MASK = '+7(%d%d%d)%d%d%d-%d%d-%d%d';
$VALUE = '1234145577';
$arValues = str_split($VALUE, 1);

$RESULT = sprintf($MASK, ...$arValues);

print_r($RESULT); // +7(123)414-55-77
Ответ написан
Комментировать
@Moshiwa Автор вопроса
Нашел для себя следующее решение:
protected $mask = [
  7 => [
    'country' => 'ru',
    'mask' => "/
       (7)?\D*     # optional country code
       (\d{3})?\D* # optional area code
       (\d{3})\D*  # first three
       (\d{2})     # first two
       (\d{2})     # second two
        /x"
  ],
  355 => [
    'country' => 'al',
    'mask' => "/
        (355)?\D*   # optional country code
        (\d{3})?\D* # optional area code
        (\d{3})\D*  # first three
        (\d{3})     # second three
         /x"
        ],
     //.....
];

public function __construct($phone = null, $code = null)
    {
        if(! $phone){
            throw new Exception('Not set phone');
        }
        $this->phone = $phone;
        if($code){
            $this->code = $code;
        }
    }

public function getMaskPhone() {
        $code = empty($this->code) ? '' : $this->code;
        $phone = empty($this->phone) ? '' : $this->phone;
        if (empty($code)) {
            return $phone;
        }

        $mask = empty(self::$mask[$code]['mask']) ? '' : self::$mask[$code]['mask'];
        if (empty($mask)) {
            return "+".$code." ".$phone;
        }

        $phone = $code.$phone;
        preg_match($mask, $phone, $matches);
        if(!isset($matches[0])){
            return false;
        }

        $country = $matches[1];
        $area = $matches[2];

        $firstPart = empty($matches[3]) ? '' : $matches[3];
        $secondPart = empty($matches[4]) ? '' : $matches[4];
        $thirdPart = empty($matches[5]) ? '' : $matches[5];
        $fourthPart = empty($matches[6]) ? '' : $matches[6];
        $fifthPart = empty($matches[7]) ? '' : $matches[7];

        $out = $firstPart;
        if (!empty($secondPart)) {
            $out .= "-".$secondPart;
        }

        if (!empty($thirdPart)) {
            $out .= "-".$thirdPart;
        }

        if (!empty($fourthPart)) {
            $out .= "-".$fourthPart;
        }

        if (!empty($fifthPart)) {
            $out .= "-".$fifthPart;
        }

        if (!empty($area)) {
            $out = "(".$area.")".$out;
        } else {
            $out = $area."-".$out;
        }

        if (!empty($country)) {
            $out = "+".$country.$out;
        }

        if(!empty($ext)) {
            $out .= "x".$ext;
        }

        return $out;
    }
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
29 мар. 2024, в 10:00
10000 руб./за проект
29 мар. 2024, в 09:59
750 руб./в час
29 мар. 2024, в 09:55
50000 руб./за проект