A good[ish] website

Web development blog, loads of UI and JavaScript topics

Strip punctuation from a string with regex using PHP

Filed under: php— Tagged with: snippets

A quick regex snippet on how to match punctuation on a string and strip them out.

// To keep letters & numbers
$string = preg_replace('/[^a-z0-9]+/i', '_', $string);

// To keep letters only
$string = preg_replace('/[^a-z]+/i', '_', $string);

// To keep letters, numbers & underscore
$string = preg_replace('/[W]+/', '_', $string);


Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!