PHP 条带标点符号

2022-08-30 13:50:44

假设我有这个:

$hello = "Hello, is StackOverflow a helpful website!? Yes!";

我想去掉标点符号,这样它就会输出为:

hello_is_stackoverflow_a_helpful_website_yes

我该怎么做?


答案 1
# to keep letters & numbers
$s = preg_replace('/[^a-z0-9]+/i', '_', $s); # or...
$s = preg_replace('/[^a-z\d]+/i', '_', $s);

# to keep letters only
$s = preg_replace('/[^a-z]+/i', '_', $s); 

# to keep letters, numbers & underscore
$s = preg_replace('/[^\w]+/', '_', $s);

# same as third example; suggested by @tchrist; ^\w = \W
$s = preg_replace('/\W+/', '_', $s);

对于字符串

$s = "Hello, is StackOverflow a helpful website!? Yes!";

结果(对于所有示例)为

Hello_is_StackOverflow_a_helpful_website_Yes_

享受!


答案 2
function strip_punctuation($string) {
    $string = strtolower($string);
    $string = preg_replace("/[:punct:]+/", "", $string);
    $string = str_replace(" +", "_", $string);
    return $string;
}

首先将字符串转换为小写,然后删除标点符号,然后用下划线替换空格(这将处理一个或多个空格,因此如果有人放置两个空格,它将仅替换为一个下划线)。


推荐