2017-04-25 116 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); 也用數字和所有類型的字符串和工程等