PHP, split string in half / Insert into the middle of a string

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

7 thoughts on “PHP, split string in half / Insert into the middle of a string

  1. Pingback: PHP, split string in half / Insert into the middle of a string | PHP-Blog.com

  2. Something a little shorter, but a lot uglier :)

    $s = “somestringofcharacters”;
    $m = “^”;

    echo preg_replace(‘/(.{‘.ceil(strlen($s)/2).’})(.*)/’, “$1$m$2”, $s);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s