PHP strip punctuation

后端 未结 4 1172
灰色年华
灰色年华 2020-12-05 00:12

Let\'s say I have this:

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

and I want to strip punctuation so it outputs as:

4条回答
  •  佛祖请我去吃肉
    2020-12-05 00:41

    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).

提交回复
热议问题