Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Created July 22, 2010 10:22
Show Gist options
  • Save RobertAudi/485814 to your computer and use it in GitHub Desktop.
Save RobertAudi/485814 to your computer and use it in GitHub Desktop.
Insert a character at a certain position in a string.
<?php
/**
* Insert a character at a certain position in a string
*
* @param string $char : The character to insert.
* @param string $string : The input string.
* @param int|string $position : The position of the insertion; if the position is set to 'random', than the position will be ... random ...
* @return string
* @author Aziz Light
*/
function insert_char_in_string( $char = '', $string = '', $position = 'random' )
{
if ( ( int ) $position > 0 )
$position--;
elseif ( ( int ) $position < 0 )
$position = strlen( $string ) - abs( $position );
elseif ( ( string ) trim( $position ) == 'random' )
$position = mt_rand( 0, ( strlen( $string ) - 1 ) );
return ( $position == 0 ) ? substr_replace( $string, $char . $string[$position], $position, 1 ) : substr_replace( $string, $string[$position] . $char, $position, 1 );
} // End of insert_char_in_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment