MattsBits
MattsBits

MattsBits

Expand or Pad a String With PHP Function  

by Matt Hawkins, 10/02/2012
Categories : PHP & MySQL

This function allows you to pad a string with a specified string or character. It inserts the padding character or string between each character of the original string.

For example if your string is "Hello World" you could use this function to pad it with space characters and return "H e l l o W o r l d".

The function is called ExpandString and accepts two arguments, $str and $pad. $str is the string that needs to be expanded. $pad is the character or string that needs to be inserted between each character of $str.


Here is the function :


<?php

function ExpandString($str,$pad) {
$string = "";
// Copy each character from source string to
// output string but add a pad character.
for($i = 0; $i < strlen($str); $i++) {
$string = $string . $str[$i] . $pad;
}
// Remove trailing pad character
return trim($string,$pad);
}

?>


Here is a script to test the function :


<?php

function ExpandString($str,$pad) {
$string = "";
// Copy each character from source string to
// output string but add a pad character.
for($i = 0; $i < strlen($str); $i++) {
$string = $string . $str[$i] . $pad;
}
// Remove trailing pad character
return trim($string,$pad);
}

echo "Expand Hello World with a space : ";
echo ExpandString("Hello World"," ");
echo "<br>";
echo "Expand 123456 with a dash : ";
echo ExpandString("123456","-");
echo "<br>";
echo "Expand ABCDEF with _-_ : ";
echo ExpandString("ABCDEF","_-_");

?>

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2022