从字符串中删除除空格以外的特殊字符

以下代码从PHP中的空间中删除字符串中的特殊字符。

//Remove special characters except space
$cleanStr = preg_replace('/[^A-Za-z0-9 ]/', '', $string);

输出:

Welcome to onitroad the world of programming

从字符串中删除特殊字符

以下代码从字符串中删除了PHP中的正则表达式模式(正则表达式)的特殊字符。

$string = "Wel%come *to( codex<world, the |world o^f pro?gramm&ing.";
//Remove special characters
$cleanStr = preg_replace('/[^A-Za-z0-9]/', '', $string);

输出:

Welcometoonitroadtheworldofprogramming
PHP中如何删除字符串中的特殊字符

可以在PHP中使用PREG_REPLACE()函数轻松删除来自字符串的特殊字符。
preg_replace()函数使用正则表达式执行搜索,并替换具有指定替换的匹配项。
在以下代码中,我们将展示如何使用PHP从字符串中删除特殊字符。

以下示例代码使用preg_replace()使用正则表达式来删除PHP中字符串的特殊字符。

清除搜索引擎优化友好的网址字符串

以下代码清除一个字符串,可以在PHP中的URI段中使用,以生成SEO友好URL。

function cleanStr($string){
    //Replaces all spaces with hyphens.
    $string = str_replace(' ', '-', $string);
    //Removes special chars.
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
    //Replaces multiple hyphens with single one.
    $string = preg_replace('/-+/', '-', $string);

    return $string;
}
$cleanStr = cleanStr($string);

输出:

Welcome-to-onitroad-the-world-of-programming
日期:2020-06-02 22:15:58 来源:oir作者:oir