8

I need to have a string that has a specified length and replace the excess characters with a letter.

e.g.

My original string is : "JOHNDOESMITH". The length should be up to 25 characters only. I need my string to become "XXXXXXXXXXXXXJOHNDOESMITH" (13 X's and 12 chars from the original string).

Anybody please tell me how to achieve this? Is there a string function for this? I've been racking my brains out for quite some time now and I still can't find a solution.

alex
  • 479,566
  • 201
  • 878
  • 984
cmyk1
  • 83
  • 1
  • 1
  • 8
  • Just out of curiosity, why do you want to do this? – Stecman Jun 27 '12 at 06:43
  • It's because of the project I'm doing. I need to send a downloadable .txt file to a bank containing the information. I'm presuming they're using Cobol so the info needs to be in some kind of format. – cmyk1 Jun 27 '12 at 07:00

3 Answers3

20

You could use str_pad() to do it...

echo str_pad($str, 25, 'X', STR_PAD_LEFT);

CodePad.

You could use str_repeat() to do it...

echo str_repeat('X', max(0, 25 - strlen($str))) . $str;

CodePad.

The length should be up to 25 characters only.

You can always run substr($str, 0, 25) to truncate your string to the first 25 characters.

alex
  • 479,566
  • 201
  • 878
  • 984
  • "The length should be up to 25 characters only" - these will output the input if it's longer than 25, not truncate it (though to be fair the OP didn't specify what should happen if over 25 characters) – Stecman Jun 27 '12 at 06:49
  • It's okay, guys. Thanks for helping me! You all are the greatest! :D – cmyk1 Jun 27 '12 at 07:02
4

We can use printf() or sprintf() function.

 $format= "%'X25s";
 printf($format, "JOHNDOESMITH");  // Prints a formatted string
 $output = sprintf($format, "JOHNDOESMITH");  // Returns a formatted string
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
2

Use the str_pad function:

$a="JOHNDOESMITH";   
$b=str_pad($a,25,'X',STR_PAD_LEFT);
print_r($b);
zaf
  • 22,776
  • 12
  • 65
  • 95