Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace last seven characters of string

Tags:

php

I have a string and I want to replace the last 7 charators of the string with "#". For example I have "MerryChristmasu87yujh7" I want to replace "87yujh7" with seven "#######". So, the final string will be "MerryChristmasu#######".

I have tried the follow code but it returns "MerryChristmasu#######1". It does not convert all seven ending characters.

$string = "MerryChristmasu87yujh7";
$match = substr($string, -7, -1);
$result = str_replace($match, "#######", $string);
like image 216
Daniel Avatar asked Feb 21 '26 10:02

Daniel


2 Answers

Should be...

$match = substr($string, -7);

... without the final -1. But in fact, it's far better done with...

$result = substr($string, 0, -7) . str_repeat('#', 7);

... or, more generic:

$coverWith = function($string, $char, $number) {
  return substr($string, 0, -$number) . str_repeat($char, $number);
};
like image 69
raina77ow Avatar answered Feb 24 '26 00:02

raina77ow


$cuttedString = substr("your string", -7);

this should do the job.

like image 32
doniyor Avatar answered Feb 23 '26 22:02

doniyor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!