PHP: Replacement of characters within a string starting from a given position

0

I need a way in PHP to replace parts of strings from a given position, for example:

String: aaa aaaaaaa Replace from 3rd character with "-" Result: aaa -------

or

String: aaaaaaa aaa Replace 7th with "-" Result: ------- aaa

or

String: aaaaaaaaaa Replace or split from any position to any other position Result: aa ------ aa Results: --- aaa ----

    
asked by anonymous 26.05.2017 / 16:25

1 answer

0

ideone

$str = "aaaaaaaaaa";
$carater="-";
$apartir=3;
$ate=7;
$ambos="ambos";
$entre="entre";
$compr=strlen($str);

if ($apartir==3){
 $nome=substr($str, $compr-$apartir, $compr);
 $right = str_pad($nome, $compr, $carater, STR_PAD_RIGHT);
}

if ($ate==7){
  $nome=substr($str, $compr-$apartir, $compr);
  $left = str_pad($nome, $compr, $carater, STR_PAD_LEFT);
}

if($ambos=="ambos"){
    $nome=substr($str, $ate, $compr);
    $both = str_pad($nome, $compr, $carater, STR_PAD_BOTH);
}

    echo $right;
    echo "\n";
    echo $left;
    echo "\n";
    echo $both;
    echo "\n";

$quant=2;

$parts = str_split($str, $quant);
$inicio = $fim = $parts[0]; 

$aux=substr($str,$quant*2,$compr);

$compl=str_replace("a",$carater,$aux);

$meio=$inicio.$compl.$fim;
echo $meio;

References:

strlen

substr

str_pad

str_split

    
26.05.2017 / 21:08