简体   繁体   中英

replacing multiple items in a string with str_replace

I have to alter two things in this example text:

example_1,example_2

I need to appear this way: example 1, example 2

So I need to replace the "_" with a space " " as well as the "," to ", " with a space. Currently I have this code below and it replaces the underscore fine, but I don't know how to also integrate the "," part in this code.

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

Would it be something like this:

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

Or, in one line you can use regex with something similar to:

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

The code above has a limitation where it won't replace the very last element in your comma-separated list. The following alleviates that problem by making the comma optional using the ? modifier.

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

That expression will now work properly but it should be noted that your final string will probably have a single space character(' ') appended to the end. Not the end of the world but should be noted.

您可以使用strtr同时执行多个替换:

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

This piece of code, would do the work:

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

echo $salida;

Array version:

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

echo $sal;
<?php

$str = 'example_1,example_2';

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

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

check codepad - http://codepad.org/am4L4v91

OR even this works -

<?php

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

echo $str;

Check code pad - http://codepad.org/2AI9Pt7x

What you could do is the following:

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

Since str_replace() accepts an array.

You could also use regular expressions which is handy when there is unexpected data like this with several spaces:

example_1, example_2 , example_3

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

Where \\s* means match 0 or more white spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM