John Melchior
John Melchior

Reputation: 427

Replace a particular character from a string from the x position of the character

I am having issue in replacing a particular character.

Example 1: format : xxx-xxx-xxx if i enter 6953 in a field and hit submit i need the result like

000-006-953

Example 2: format : 1ax-xxx-xxx if i enter 6953 in a field and hit submit i need the result like

1a0-006-953

Example 3: format : 1ax-xxx-xxs if i enter 6953 in a field and hit submit i need the result like

1a0-069-53s

The format will be dynamic and result will be based on the format and the input value.

I tried this code

$a = '1axxxxx99';


$str = 6938;


$f_str = str_pad($str, strlen($a), "0", STR_PAD_LEFT);

for ($i = count($c) - 1; $i >= 0; $i--) {
    $f_str = substr_replace($f_str, '-', '-' . $c[$i], 0);
}

echo $f_str;

Upvotes: 1

Views: 91

Answers (2)

Toto
Toto

Reputation: 91488

Here is my way to go:

$formats = array(
    'xxx-xxx-xxx',
    '1ax-xxx-xxx',
    '1ax-xxx-xxs',
);
$data = '6953';
foreach($formats as $format) {
    echo "$format --> ";
    $j = strlen($data)-1;
    for($i=strlen($format)-1; $i>=0 ; $i--) {
        if ($format[$i] == 'x') {
            if ($j >= 0) {
                $format[$i] = $data[$j];
                $j--;
            } else {
                $format[$i] = 0;
            }
        }
    }
    echo "$format\n";
}

Output:

xxx-xxx-xxx --> 000-006-953
1ax-xxx-xxx --> 1a0-006-953
1ax-xxx-xxs --> 1a0-069-53s

Upvotes: 2

Kulvar
Kulvar

Reputation: 1179

// For testing
$joker = '*';
$format = '1a**-***-***';
$input = 6589; // work with '6589' too

// Code start here
$input .= '';
$result = $format;
$i = strlen($format)-1;
$j = strlen($input)-1;
while($i > -1) {
    if($result[$i] === $joker) {
        if($j > -1) {
            $result[$i] = $input[$j];
            --$j;
        }
        else {
            $result[$i] = '0';
        }
    }
    --$i;
}
// Output for test
echo $result;

Upvotes: 0

Related Questions