用str_replace替换字符串中的多个项目

时间:2013-06-10 16:58:06

标签: php str-replace

我必须在此示例文本中更改两件事:

example_1,example_2

我需要这样出现: example 1, example 2

所以我需要用空格“”替换“_”以及用空格替换“,”到“,”。 目前我在下面有这个代码,它取代了下划线,但我不知道如何在这段代码中集成“,”部分。

str_replace('_', ' ', $test)

会是这样的:

str_replace(('_', ' ',),(',', ' '), $test)

5 个答案:

答案 0 :(得分:5)

或者,在一行中,您可以使用类似于以下内容的正则表达式:

preg_replace("/_(.*)\,/", " \\1, ", "Example_1,Example_2");

上面的代码有一个限制,它不会替换逗号分隔列表中的最后一个元素。以下通过使用逗号选项来缓解这个问题?改性剂。

echo preg_replace("/_(\d)(\,?)/", " \\1\\2 ", "Example_1,Example_2");

该表达式现在可以正常工作,但应该注意,您的最终字符串可能会在末尾附加一个空格字符('')。不是世界末日,而是应该注意。

答案 1 :(得分:3)

您可以使用strtr同时进行多次替换:

strtr($test, array('_' => ' ', ',' => ', '));

答案 2 :(得分:1)

这段代码可以完成工作:

$cadena = "example_1,example_2";
$salida = str_replace("_", " ", $cadena);
$salida = str_replace(",", ", ", $salida);

echo $salida;

数组版本:

$buscar = array("_",",");
$reeemplazar = array(" ",", ");
$sal = str_replace($buscar, $reeemplazar, $cadena);

echo $sal;

答案 3 :(得分:0)

<?php

$str = 'example_1,example_2';

$str = str_replace('_', ' ', $str);

$str = str_replace(',', ', ', $str);
echo $str;

检查键盘 - http://codepad.org/am4L4v91

或者即便如此 -

<?php

$str = 'example_1,example_2';
$match = array('_' =>' ', ',' => ', ');
$str = strtr($str, $match);

echo $str;

检查代码表 - http://codepad.org/2AI9Pt7x

答案 4 :(得分:0)

您可以做的是:

$string = 'example_1,example_2';
$new = str_replace(array('_', ','), array(' ', ', '), $string);
echo $new;

由于str_replace()接受数组。

您还可以使用正则表达式,当存在多个空格时出现意外数据时非常方便:

  

example_1,example_2,example_3

$string = 'example_1, example_2   , example_3';
$new = preg_replace(array('#_#', '#\s*,\s*#'), array(' ', ', '), $string);
echo $new;

\s*表示匹配0个或更多空格。

相关问题