Created
July 12, 2012 15:21
-
-
Save sgmurphy/3098836 to your computer and use it in GitHub Desktop.
mb_str_replace for PHP
This file contains hidden or 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 | |
/** | |
* Replace all occurrences of the search string with the replacement string. | |
* | |
* @author Sean Murphy <[email protected]> | |
* @copyright Copyright 2012 Sean Murphy. All rights reserved. | |
* @license http://creativecommons.org/publicdomain/zero/1.0/ | |
* @link http://php.net/manual/function.str-replace.php | |
* | |
* @param mixed $search | |
* @param mixed $replace | |
* @param mixed $subject | |
* @param int $count | |
* @return mixed | |
*/ | |
if (!function_exists('mb_str_replace')) { | |
function mb_str_replace($search, $replace, $subject, &$count = 0) { | |
if (!is_array($subject)) { | |
// Normalize $search and $replace so they are both arrays of the same length | |
$searches = is_array($search) ? array_values($search) : array($search); | |
$replacements = is_array($replace) ? array_values($replace) : array($replace); | |
$replacements = array_pad($replacements, count($searches), ''); | |
foreach ($searches as $key => $search) { | |
$parts = mb_split(preg_quote($search), $subject); | |
$count += count($parts) - 1; | |
$subject = implode($replacements[$key], $parts); | |
} | |
} else { | |
// Call mb_str_replace for each subject in array, recursively | |
foreach ($subject as $key => $value) { | |
$subject[$key] = mb_str_replace($search, $replace, $value, $count); | |
} | |
} | |
return $subject; | |
} | |
} | |
?> |
@vadviktor @sgmurphy you are absolutely right! Just checked it with PHP 5.4
Иногда можно использовать и такой простой способ
// БЫСТРАЯ ЗАМЕНА МАКРОСА ДЛЯ МУЛЬТИБАЙТОВЫХ СТРОК
$title = 'Текст на русском и #NAME# теперь в строке';
$name = 'Мария';
$macros = '#NAME#';
$macLen = mb_strlen($macros);
$macPos = mb_strpos($title, $macros);
if($macPos !== false)
{
$start = mb_substr($title, 0, $macPos);
$end = mb_substr($title, $macPos + $macLen);
$title = $start.$name.$end;
}
echo $title; // Текст на русском и Мария теперь в строке
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a hint, str_replace itself is utf-8 ready, thats why mb_str_replace does not exist.