Friday, May 6, 2011

Stripping everything but alphanumeric chars from a string in PHP

I'd like a regexp or other string which can replace everything except alphanumeric chars (a-z and 0-9) from a string. All things such as ,@#$(@*810 should be stripped. Any ideas?

Edit: I now need this to strip everything but allow dots, so everything but a-z, 1-9, .. Ideas?

From stackoverflow
  • /[^a-z0-9.]/
    

    should do the trick

    Click Upvote : How can i change that to allow only dots (i.e .)?
    Gumbo : @ Click Upvote: `[^.]`
    Click Upvote : Full reg exp please? I don't know the syntax
  • Try:

    $string = preg_replace ('/[^a-z0-9]/i', '', $string);
    

    /i stands for case insensitivity (if you need it, of course).

  • $string = preg_replace("/[^a-z0-9.]+/i", "", $string);
    

    Matches one or more characters not a-z 0-9 [case-insensitive], or "." and replaces with ""

    Click Upvote : How can i change that to allow only dots (i.e .)?
    gnarf : Adjusted to also include "."
    Gumbo : You don’t need to escape the dot inside the character set.
    gnarf : @gumbo - thanks learned something myself from this one :)
  • I like using [^[:alnum:]] for this, less room for error.

    preg_replace('/[^[:alnum:]]/', '', "(ABC)-[123]"); // returns 'ABC123'
    

0 comments:

Post a Comment