Jump to content

randomly pad a string


uppercasefive

Recommended Posts

So I've got a string

 

$string = "1234567";

 

I want to randomly pad it with random characters from an array, example:

 

$string = "12xa3b45ds67";

 

I can't think of a good way to accomplish this, at least not without excessive code. Is there a PHP function to do this, or will I have to find one?

Link to comment
https://forums.phpfreaks.com/topic/160690-randomly-pad-a-string/
Share on other sites

Try:

 

function pad_string($str, $arr)
{
$amt=(strlen($str)/2);
$split = str_split($str);
$ori = $split;
for($i = 0;$i < $amt;$i++)
{
	$replace = rand(0, count($split));
	array_splice($split, $replace, 0, $arr[rand(0, count($arr))]);
}
return implode('', $split);
}

$arr = array('x', 'b', 'c', 'd');
$str = '436275547';
$new_str = pad_string($str, $arr);

echo 'Original String: ' . $str . '<br />';
echo 'Original Length: ' . strlen($str) . '<br />';
echo 'New String: ' . $new_str . '<br />';
echo 'New String Length: ' . strlen($new_str) . '<br />';

 

Output:

 

 

Original String: 4362755647

Original Length: 10

New String: 4c36275564b7cdx

New String Length: 15

 

 

Arg, I edited that last post wrong.. And now I can't edit it again.. this is it:

 

function pad_string($str, $arr)
{
$amt = (strlen($str)/2);
$split = str_split($str);
$num = 0;
while($num < $amt)
{
	array_splice($split, rand(0, count($split)), 0, $arr[rand(0, count($arr))]);
	$num++;
}
return implode('', $split);
}

$arr = array('x', 'b', 'c', 'd');
$str = '4362755647';
$new_str = pad_string($str, $arr);

echo 'Original String: ' . $str . '<br />';
echo 'Original Length: ' . strlen($str) . '<br />';
echo 'New String: ' . $new_str . '<br />';
echo 'New String Length: ' . strlen($new_str) . '<br />';

 

Output:

 

Original String: 4362755647

Original Length: 10

New String: 4c36275564b7cdx

New String Length: 15

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.