PHP strip punctuation

后端 未结 4 1177
灰色年华
灰色年华 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:34

    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.

提交回复
热议问题