非字母数字字符替换为单个空格

时间:2012-05-23 15:58:21

标签: php

这就是我试图让搜索引擎选择以Doe J而不是Doe,J输入的名称。

这是我的代码:

$sql_where = array();

if (isset($_GET['name'])) {

    echo "Searched: {$_GET['name']}<br>";

    $names = explode(' ', trim(preg_replace('/ +/', ' ', $_GET['name'])));
    $names_cnt = count($names);

    if (2 == $names_cnt) {

        foreach ($names as $name_idx => $name) {

            if (($name_idx+1) == $names_cnt) {
                // last one
                $sql_where[] = "
                    (full_name like '% {$name}%')
                    ";
            } else {
                // first one
                $sql_where[] = "
                    (full_name like '{$name}%')
                    ";
            }
        }
    } else {

        $sql_where[] = "
            (full_name like '" . $DB->cleanString($_GET['name']) . "%')
            ";

我尝试了/[^a-zA-Z0-9 ]/以及其他一些不成功的变体。

1 个答案:

答案 0 :(得分:2)

echo preg_replace( "`[^a-zA-Z0-9]+`", " ", $string); 
//replaces all non alpha numeric characters as " " 
//(and will not have duplicate spaces)

DEMO:http://codepad.org/7Ltx3kcr