Search code examples
phpjqueryregexclean-urlscode-cleanup

Smart trim() option in php and jQuery


This is the problem that I have in PHP and jQuery. I want to make a "smart" function that will not only clean white space, but also a certain character at the beginning and end of the string. Why?

I made administration panel who manage with subdomains. Allowed characters is [a-z0-9-.]. If someone accidentally write "-my.domanin." or ".my-domain" or "-my-domain-" or a similar variation is problem. I need to trim that to look like this "my-domain" or "my.domain"

Is this possible? Thanks!


Solution

  • function mytrim($stringToTrim) {
        return trim($tringToTrim, " \t\n\r\0\x0B.-");
    }
    

    The first part of the string, " \t\n\r\0\x0B", strips white space from the beginning and ends and the second part, ".-" strips the "." and "-" characters.

    Clearly you could just use trim() in your script, I just put it in a function for the example.