PHP带标点符号。

假设我有这个:
$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_ 请享用!     
function strip_punctuation($string) {
    $string = strtolower($string);
    $string = preg_replace(\"/[:punct:]+/\", \"\", $string);
    $string = str_replace(\" +\", \"_\", $string);
    return $string;
}
首先将字符串转换为小写字母,然后删除标点符号,然后用下划线替换空格(这将处理一个或多个空格,因此,如果有人放置两个空格,则只能替换一个下划线)。     
没有正则表达式:
<?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
?>
    
我会选择这样的东西:
$str = preg_replace(\'/[^\\w\\s]/\', \'\', $str);
我不知道这是否比您想要的要广泛,但这听起来像您正在尝试做的事情。 我还注意到您在示例中用下划线替换了空格。我要使用的代码是:
$str = preg_replace(\'/\\s+/\', \'_\', $str);
请注意,这还将把多个空格折叠为一个下划线。     

要回复问题请先登录注册