我有一个包含字符串的数组,其中一些字符串包含点('.')。
我必须重复一遍。我不想用str_replace来做这件事。
所以,我需要用下划线代替这些点。
例如:
for($data as $key=>$value){
print_r($value);
}
比方说输出是如何的:
'Hello. I have two dots. Please replace them!'
我们想要的是:
'Hello_ I have two dots_ Please replace them!'
提前感谢
这是codegolf还是什么?
无论如何,这里有一个解决方案:
$text='Hello. I have two dots. Please replace them!';
echo IHateStrReplace(".","_",$text);
function IHateStrReplace($replace_from,$replace_to,$input)
{
$result="";
for($i=0;$i<strlen($input);$i++)
{
$result.= ($input[$i]==$replace_from)?$replace_to:$input[$i];
}
return $result;
}
http://3v4l.org/Cjp4G
怎么样
$original_string = 'Hello. I have two dots. Please replace them!';
$exploded_string = explode('.' , $original_string);
$new_string = implode('_' , $exploded_string);
echo strtr('Hello. I have two dots. Please replace them!', '.', '_');
字符串翻译对字符串进行逐字节的翻译。
您可以使用preg_replace。http://nl3.php.net/preg_replace
$var = 'Hello. I have two dots. Please replace them!';
echo preg_replace('#'.#', '_', $var);
Regex在替换单个字符方面做得太过火了,但如果你必须避免str_replace()
,那么这就可以了:
foreach($data as $key => $value){
$data[$key] = preg_replace('/'./', '_', $value);
}
print_r($data);
对于未来的搜索者来说,strtr()
(字符串翻译)翻译单个字符,因此将其与array_map相结合可以获得一个简洁的解决方案:
// Push every item in the array through strtr()
$array = array_map('strtr', $array, ['.', '_']);
然而,在基准测试中,我发现strtr()
比str_replace()
慢,所以我倾向于使用它。