Set string with specified length in PHP

I need to have a string with the specified length and replace the extra characters with a letter.

eg.

My initial line is "JOHNDOESMITH". The length should be no more than 25 characters. I need my string to become "XXXXXXXXXXXXXXJOHNDOESMITH" (13 X and 12 characters from the original string).

Someone please tell me how to achieve this? Is there a string function for this? I have been racking my brains for quite some time, and I still cannot find a solution.

+6
source share
3 answers

You can use str_pad() to do this ...

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

CodePad

You can use str_repeat() to do this ...

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

CodePad

The length should be no more than 25 characters.

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

+12
source

Try the sprintf() function

  $format= "%'X25s"; echo sprintf($format, "JOHNDOESMITH"); 
+4
source

Use the str_pad function:

 $a="JOHNDOESMITH"; $b=str_pad($a,25,'X',STR_PAD_LEFT); print_r($b); 
+2
source

Source: https://habr.com/ru/post/919094/


All Articles