Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active December 24, 2022 19:41
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save stemar/8287074 to your computer and use it in GitHub Desktop.
Save stemar/8287074 to your computer and use it in GitHub Desktop.
Multibyte substr_replace(). The mbstring library PHP < 7.x doesn’t come with a multibyte equivalent of substr_replace(). This function behaves exactly like substr_replace() even when the arguments are arrays.
<?php
function mb_substr_replace($string, $replacement, $start, $length=NULL) {
if (is_array($string)) {
$num = count($string);
// $replacement
$replacement = is_array($replacement) ? array_slice($replacement, 0, $num) : array_pad(array($replacement), $num, $replacement);
// $start
if (is_array($start)) {
$start = array_slice($start, 0, $num);
foreach ($start as $key => $value)
$start[$key] = is_int($value) ? $value : 0;
}
else {
$start = array_pad(array($start), $num, $start);
}
// $length
if (!isset($length)) {
$length = array_fill(0, $num, 0);
}
elseif (is_array($length)) {
$length = array_slice($length, 0, $num);
foreach ($length as $key => $value)
$length[$key] = isset($value) ? (is_int($value) ? $value : $num) : 0;
}
else {
$length = array_pad(array($length), $num, $length);
}
// Recursive call
return array_map(__FUNCTION__, $string, $replacement, $start, $length);
}
preg_match_all('/./us', (string)$string, $smatches);
preg_match_all('/./us', (string)$replacement, $rmatches);
if ($length === NULL) $length = mb_strlen($string);
array_splice($smatches[0], $start, $length, $rmatches[0]);
return join($smatches[0]);
}
@JBlond
Copy link

JBlond commented Feb 4, 2015

Top work!

@leealex
Copy link

leealex commented May 11, 2018

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment