PHP如何去掉指定字元?
在PHP中可以使用「str_replace()」函數去掉指定字元,該函數會將子字串進行替換,其語法是「str_replace(sea,rep,sub) 」,使用時只需呼叫該函數將指定字元替換為空即可。
程式碼範例
基本範例
<?php // 賦值: <body text='black'> $bodytag = str_replace("%body%", "black", "<body text='%body%'>"); // 賦值: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); // 賦值: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // 賦值: 2 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; ?>
替換範例
<?php // 替換順序 $str = "Line 1nLine 2rLine 3rnLine 4n"; $order = array("rn", "n", "r"); $replace = '<br />'; // 首先替換 rn 字元,因此它們不會被兩次轉換 $newstr = str_replace($order, $replace, $str); // 輸出 F ,因為 A 被 B 替換,B 又被 C 替換,以此類推... // 由於從左到右依次替換,最終 E 被 F 替換 $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject); // 輸出: apearpearle pear // 由於上面提到的原因 $letters = array('a', 'p'); $fruit = array('apple', 'pear'); $text = 'a p'; $output = str_replace($letters, $fruit, $text); echo $output; ?>以上就是PHP如何去掉指定字元?的詳細內容,更多請關注TW511.COM其它相關文章!