2012-12-20 359 views
2

的最後七個字符我有一個​​字符串,我想用「#」替換字符串的最後7個charators。例如,我有「MerryChristmasu87yujh7」我想用七個「#######」替換「87yujh7」。所以,最後的字符串將是「MerryChristmasu #######」。替換字符串

我曾嘗試後續代碼,但它返回「MerryChristmasu ####### 1」。它不會轉換全部7個結尾字符。

$string = "MerryChristmasu87yujh7"; 
$match = substr($string, -7, -1); 
$result = str_replace($match, "#######", $string); 

回答

7

應該是...

$match = substr($string, -7); 

...沒有最終-1。但實際上,它是遠遠更好地與...

$result = substr($string, 0, -7) . str_repeat('#', 7); 

做...或者,更通用的:

$coverWith = function($string, $char, $number) { 
    return substr($string, 0, -$number) . str_repeat($char, $number); 
}; 
+0

感謝您的幫助,精美的作品:) –

1
$cuttedString = substr("your string", -7); 

本應該做的工作。