Created
July 22, 2010 10:22
-
-
Save RobertAudi/485814 to your computer and use it in GitHub Desktop.
Insert a character at a certain position in a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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