PHP 条形标点符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5689918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP strip punctuation
提问by test
Let's say I have this:
假设我有这个:
$hello = "Hello, is StackOverflow a helpful website!? Yes!";
and I want to strip punctuation so it outputs as:
我想去掉标点符号,所以它输出为:
hello_is_stackoverflow_a_helpful_website_yes
How can I do that?
我怎样才能做到这一点?
回答by Wh1T3h4Ck5
# 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);
for string
对于字符串
$s = "Hello, is StackOverflow a helpful website!? Yes!";
result (for all examples) is
结果(对于所有示例)是
Hello_is_StackOverflow_a_helpful_website_Yes_
Hello_is_StackOverflow_a_helpful_website_Yes_
Enjoy!
享受!
回答by Rafe Kettler
function strip_punctuation($string) {
$string = strtolower($string);
$string = preg_replace("/[:punct:]+/", "", $string);
$string = str_replace(" +", "_", $string);
return $string;
}
First the string is converted to lower case, then punctuation is removed, then spaces are replaced with underscores (this will handle one or more spaces, so if someone puts two spaces it will be replaced by only one underscore).
首先将字符串转换为小写,然后删除标点符号,然后用下划线替换空格(这将处理一个或多个空格,因此如果有人输入两个空格,它将仅被一个下划线替换)。
回答by quantme
Without regular expressions:
没有正则表达式:
<?php
$hello = "Hello, is StackOverflow a helpful website!? Yes!"; // original string
$unwantedChars = array(',', '!', '?'); // create array with unwanted chars
$hello = str_replace($unwantedChars, '', $hello); // remove them
$hello = strtolower($hello); // convert to lowercase
$hello = str_replace(' ', '_', $hello); // replace spaces with underline
echo $hello; // outputs: hello_is_stackoverflow_a_helpful_website_yes
?>
回答by Justin Morgan
I'd go with something like this:
我会用这样的东西:
$str = preg_replace('/[^\w\s]/', '', $str);
I don't know if that's more broad than you're looking for, but it sounds like what you're trying to do.
我不知道这是否比您想要的更广泛,但这听起来像是您想要做的。
I also notice you've replaced spaces with underscores in your sample. The code I'd use for that is:
我还注意到您在示例中用下划线替换了空格。我为此使用的代码是:
$str = preg_replace('/\s+/', '_', $str);
Note that this will also collapse multiple spaces into one underscore.
请注意,这也会将多个空格折叠为一个下划线。