There’s got to be an easier way of doing this…. I wanted to harden an existing random password generator by insterting a random special character into the middle of the string. Task at hand: split string into two parts, left and right; return a string with the special characters in the middle of the left, right parts.
Here’s what I came up with in PHP:
$str = "somestringofcharacters";
$middle = "^";
$half = (int) ( (strlen($str) / 2) ); // cast to int incase str length is odd
$left = substr($str, 0, $half);
$right = substr($str, $half);
echo $left.$middle.$right;
This is what it would look like in python:
>>> s = "somestringofcharacters"
>>> m = "^"
>>> s[:len(s)/2] + m + s[len(s)/2:]
'somestringo^fcharacters'
Pingback: PHP, split string in half / Insert into the middle of a string | PHP-Blog.com
Something a little shorter, but a lot uglier :)
$s = “somestringofcharacters”;
$m = “^”;
echo preg_replace(‘/(.{‘.ceil(strlen($s)/2).’})(.*)/’, “$1$m$2″, $s);
@trevis – To be honest, my python one-liner is a bit obtuse as well.
one-liner:
$newstring=substr_replace($orig_string, $insert_string, $position, 0);
How could you put a “-” every 5 letters in python?
implode( $insert, str_split( $original, ( strlen($original) / 2 ) ) )
Thanks for you solution to split at half a string! very useful! :)