How to pad a string to a specific length with another string in PHP

7 Answers

0 votes
$s = "PHP";
echo str_pad($s, 10, "-", STR_PAD_LEFT); // 7 (-) + 3 (PHP)

    
/*
run:

-------PHP 
     
*/

 



answered Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 12, "-@", STR_PAD_LEFT); 

    
/*
run:

-@-@-@-@-PHP  
     
*/

 



answered Feb 29, 2016 by avibootz
edited Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 12, "-@", STR_PAD_RIGHT); 

    
/*
run:

PHP-@-@-@-@-  
     
*/

 



answered Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 12, "-", STR_PAD_BOTH); 

    
/*
run:

----PHP-----  
     
*/

 



answered Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 4, "_"); 

    
/*
run:

PHP_  
     
*/

 



answered Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 3, "--"); 

    
/*
run:

PHP  
     
*/

 



answered Feb 29, 2016 by avibootz
0 votes
$s = "PHP";
echo str_pad($s, 6, "-", STR_PAD_BOTH); 

    
/*
run:

-PHP--
     
*/

 



answered Feb 29, 2016 by avibootz

Related questions

1 answer 195 views
1 answer 191 views
191 views asked Apr 28, 2016 by avibootz
1 answer 93 views
1 answer 81 views
...