用於從字串中去除非字母數字字元的 PHP 程式


要從字串中刪除非字母數字字元,程式碼如下 -

示例

 現場演示

<?php
$my_str="Thisis!@sample*on&ly)#$";
$my_str = preg_replace( '/[^a-z0-9]/i', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo($my_str);
?>

輸出

The non-alphanumeric characters removed gives the string as Thisissampleonly

函式“preg_replace”用於從字串中刪除字母數字字元。正則表示式用於過濾出字母數字字元。該字串先前已定義,並在該字串上呼叫函式“preg_replace”,並將重組後的字串顯示在控制檯上。

示例

 現場演示

<?php
$my_str="This!#is^&*a)(sample*+_only";
$my_str = preg_replace( '/[W]/', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as ";
echo($my_str);
?>

輸出

The non-alphanumeric characters removed gives the string as Thisisasample_only

這裡唯一的區別是使用了不同的正則表示式。它與前一個正則表示式意思相同,只是寫法不同。

更新於:2020-07-02

826 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.