str_replace() equivalent for Multi-byte string like UTF-8

29 Aug

As you may know str_replace does not work when you pass multi-byte strings to $search parameter, so below is an equivalent mb_replace() to str_replace(). Note that $search parameter must be an array.

function mb_replace($search, $replace, $subject)
$size = mb_strlen($subject, 'UTF-8');

$search = array($search);

for($i = 0; $i < sizeOf($search); $i++)
for($j = 0; $j < $size; $j++)
$ch = mb_substr($subject, $j, 1, 'UTF-8');

if($ch == $search[$i])
$subject = mb_substr($subject, 0, $j, 'UTF-8').$replace[$i].mb_substr($subject, $j + 1, $size - $j, 'UTF-8');

return $subject;

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: