Search code examples
regexnumberspreg-replaceletter

Simple regex problem!


I want to remove everything from a string except numbers, letters, _ (underscore) and : (colon)

It's PREG and I've only come across #\W#, but it removes the : (colon).

Any help is appreciated, thanks!


Solution

  • [^\w:]+ - Remove anything that isn't ([^...]) a letter, digit, underscore (\w) or colon (:).

    Sample code:

    $ptn = "/[^\w:]+/";
    $str = "Hello~~~ World+++: 123";
    echo preg_replace($ptn, "", $str);
    

    Outputs: HelloWorld:123