2017-04-25 81 views
-1

我想用特殊条件替换某些字符。 像替换字符串中的特殊字符

所以如果

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)

+5

通常你必须尝试这样做会发生之前... –

+0

所以我们在那里做功课? – Troyer

+2

在[所以]你应该尝试**自己编写代码**。后** [做更多的研究](//meta.stackoverflow.com/questions/261592)**如果你有问题,你可以**发布你已经尝试**与清楚的解释是什么是'工作**并提供[** Minimal,Complete和Verifiable示例**](// stackoverflow.com/help/mcve)。我建议阅读[问]一个好问题和[完美问题](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要参加[游览]并阅读[this](// meta.stackoverflow.com/questions/347937/)**。 –

回答

0

使用带有键和值的数组,并在foreach循环中使用str_replace函数来替换key值

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

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

例如,我们有:

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

上面将取代 'ASD' 与 'QWE' 和将输出:

Hello, qwe! 


又如:

<?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; 
?> 

而第二个例子将替换“ASD”,这是在与'美国能源部和将输出的字符串的中间位置:

Hello, JOHNdoe123! 


对于第二个问题你应该使用:

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

注意: str_replace($ symbolToBeplaplaced,$ substitutionSymbol,$ variable); 也用数字和所有类型的字符串和工程等

相关问题