Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set string to a specified length in PHP

Tags:

string

php

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.

like image 247
cmyk1 Avatar asked Jun 27 '12 06:06

cmyk1


People also ask

How do I limit the length of a string in PHP?

The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object.

What is strlen () used for in PHP?

The strlen() function returns the length of a string.


2 Answers

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.

like image 121
alex Avatar answered Oct 24 '22 21:10

alex


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

 $format= "%'X25s";
 printf($format, "JOHNDOESMITH");  // Prints a formatted string
 $output = sprintf($format, "JOHNDOESMITH");  // Returns a formatted string
like image 20
KV Prajapati Avatar answered Oct 24 '22 21:10

KV Prajapati