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
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

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.