PHP 带标点符号

标签 php regex

假设我有这个:

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

我想去掉标点符号,输出为:

hello_is_stackoverflow_a_helpful_website_yes

我该怎么做?

最佳答案

# 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_

享受吧!

关于PHP 带标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5689918/

相关文章:

php - 复选框选中数据库中是否存在值

php - 如何编写 MySQL 查询 where Date1 TO Date2?

java - 在 List.contains(String) 的情况下部分匹配字符串

regex - 用于替换文件中第一次出现的 sed 命令不起作用

php - 正则表达式:找到不包含任何单词的部分

regex - Perl 提取文本

php - 以线程安全的方式创建文件

php - MYSQL 列中的 Javascript 倒数计时器

php - Flash和PHP库在浏览器中录制声音并保存到.wav文件?

java - 如何从字符串中提取 Unix 风格的本地文件路径?