PHP: Character substitution within a string a parti of a certain position

Asked

Viewed 546 times

0

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

String: aaaaaaaaaa Replace from the character by "-" Result: aaa-------

or

String: aaaaaaaaaa Replace until the 7th character by "-" Result: ------aaa

or

String: aaaaaaaaaa Replace it or move it from any position to any other position Result: aa-----aa Result: --aaa----

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

replace

str_pad

str_split

  • Leo very grateful, it was exactly what I needed. It was of great help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.