从字符串中替换特殊字符

时间:2017-04-25 14:11:41

标签: php str-replace

我想用特殊条件替换另一个角色。 喜欢

所以,如果

a string contains _ is then replace it with .
a string contains __ is then replace it with _ (remove single _ multiple _ )
a string starting with # then replace it with $
a string starting with ## then replace it with #

我试过了

str_replace('_', '.', $string);

但它将所有_替换为。我不想替换所有_我只想替换单个位于_的(' 4__69'给4..69)

2 个答案:

答案 0 :(得分:0)

使用带有键和值的数组,并在foreach循环用户str_replace函数中用值

替换键
$string_spe = array("__"=>"_","_"=>".","##"=>"#","#"=>"$");

$string_val ="__HI This is me";
foreach($string_spe as $key => $value){
 $string_val =str_replace($key,$value,$string_val);
}

答案 1 :(得分:0)

For example we have:

<?php
$text = "Hello, asd!"; //Random text
$var = str_replace("asd", "qwe", $text); //Replacing 'asd' with 'qwe' everywhere
echo $var;
?>

The above will replace 'asd' with 'qwe' and will output:

Hello, qwe!


Another example:

<?php
$text = "Hello, JOHNasd123!"; //Random text - note 'asd' is in the middle of the string
$var = str_replace("asd", "qwe", $text); //Replacing 'asd' with 'doe' everywhere
echo $var;
?>

And the second example will replace 'asd' which is in the middle of the string with 'doe' and will output:

Hello, JOHNdoe123!


For the second question you should use:

str_replace("__", ".", $string); //Note that the underlines '__' are two!

Note: str_replace($symbolToBeReplaced, $replacingSymbol, $variable); Also works with numbers and all kind of strings and etc.