首頁 >後端開發 >PHP問題 >PHP如何去掉指定字元?

PHP如何去掉指定字元?

Guanhui
Guanhui原創
2020-06-12 17:01:546374瀏覽

PHP如何去掉指定字元?

PHP如何去掉指定字元?

在PHP中可以使用“str_replace()”函數去掉指定字符,該函數會將子字串進行替換,其語法是“str_replace(sea,rep,sub) ”,使用時只需呼叫該函數將指定字元替換為空即可。

程式碼範例

基本範例

<?php
// 赋值: <body text=&#39;black&#39;>
$bodytag = str_replace("%body%", "black", "<body text=&#39;%body%&#39;>");
// 赋值: 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 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = &#39;<br />&#39;;
// 首先替换 \r\n 字符,因此它们不会被两次转换
$newstr = str_replace($order, $replace, $str);
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search  = array(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;);
$replace = array(&#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;);
$subject = &#39;A&#39;;
echo str_replace($search, $replace, $subject);
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array(&#39;a&#39;, &#39;p&#39;);
$fruit   = array(&#39;apple&#39;, &#39;pear&#39;);
$text    = &#39;a p&#39;;
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>

推薦教學: 《PHP

#

以上是PHP如何去掉指定字元?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn