使用 PHP 函數去除字串 (String) 內一些字元
當編寫 PHP 或其他程式, 要經常處理字串的操作, 最普遍的算是需要去除字串內的某些字元。
這章課程很簡單的討論如何去除字串內的某些字元
例子一:
我們需要搜尋目錄內的 jpg 圖片檔案, 當然也可以搜尋目錄內的任何檔案。
在先前的例子中, 我們需要搜尋 photo-keung.jpg 的圖片檔案。假如我們只需要檔案的名稱 (photo-keung), 這樣我們便要考慮如何去除圖片檔案的副案名稱 (.jpg)了。 簡單來說, 就是要去除字串最後的4個字元 (.jpg)。
photo-keung.jpg => photo-keung
加入以下 PHP 語言於 HTML 文件中:
<body>
<p>PHP Trim or Replace Characters in String</p>
<?php
$pic = "photo-keung.jpg";
//remove the last four character (i.e. .jpg) from $pic
$pic = substr_replace($pic, "", -4);
echo "The pic name now is: " . $pic;
?>
</body>
</html>
將以上文件儲存成 php-trim-or-replace-character-in-string-1.php PHP 檔案.
測試 php-trim-or-replace-character-in-string-1.php 是否可以正常執行.
PHP 實例:
瀏 灠 器 應 出 現 :
例子二: 使用 rtrim() 函數去除字串最後的空白 (white space)
<body>
<p>PHP Trim or Replace Characters in String</p>
<?php
$myName = "Alex ";
// Use strlen() function to check the length of string
echo "Length of myName is: " . strlen ($myName);
echo "<Br />";
// Use rtrim() function to remove the white space at the end
$myName = rtrim($myName);
// Use strlen() function to check the length after trim
echo "Length of myName after trim is: " . strlen ($myName);
?>
</body>
</html>
將以上文件儲存成 php-trim-or-replace-character-in-string-2.php PHP 檔案.
測試 php-trim-or-replace-character-in-string-2.php 是否可以正常執行.
PHP 實例:
瀏 灠 器 應 出 現 :
Length of myName is: 5
Length of myName after trim is: 4
例子三: 使用 substr_replace() 函數去除字串最後的空白 (white space)
當然, 你也可以使用例子一的 substr_replace() 函數來完成例子二的工作.
<body>
<p>PHP Trim or Replace Characters in String</p>
<?php
$myName = "Alex ";
// Use strlen() function to check the length of string
echo "Length of myName is: " . strlen ($myName);
echo "<Br />";
// Use substr_replace() function to remove the white space at the end
$myName = substr_replace($myName, "", -1);
// Use strlen() function to check the length after trim
echo "Length of myName after substr_replace is: " . strlen ($myName);
?>
</body>
</html>
將以上文件儲存成 php-trim-or-replace-character-in-string-3.php PHP 檔案.
測試 php-trim-or-replace-character-in-string-3.php 是否可以正常執行.
PHP 實例:
瀏 灠 器 應 出 現 :
Length of myName is: 5
Length of myName after substr_replace is: 4