Removing unnecessary dots in a URL with preg_replace

Discussion in 'PHP' started by qwikad.com, Oct 4, 2013.

  1. #1
    Let's say somebody post URLs that look like this:


    http:/ /something.com.
    http:/ /something.org.
    http:/ /something.info.

    or like this:

    http:/ /something.com...
    http:/ /something.org...
    http:/ /something.info...

    or like this:

    ...http:/ /something.com
    ...http:/ /something.org
    ...http:/ /something.info

    Is there a way to clean up URLs from any dots that are not supposed to be there?

    Any input will be appreciated.
     
    qwikad.com, Oct 4, 2013 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    You can use the trim function: $url = trim($url, '.');
     
    ThePHPMaster, Oct 4, 2013 IP
  3. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,374
    Likes Received:
    1,721
    Best Answers:
    31
    Trophy Points:
    475
    #3
    Thanks, ThePHPMaster.

    Here's what I am using. Was poking around and came upon this somewhere:


    $text = preg_replace( '/(\b)(http|ftp|https|mailto)([\:\/\/])([A-z0-9~!@$%&*()_+:?,.\/;=#-]{2,}[A-z0-9~@$%&*_+\/=])/', " $2$3$4 ", $text);
    Code (markup):

    I decided to simply put a space on each end of a link, instead of trying to strip all / any characters that may come in contact with it (which in my case used to interfere with a link's accuracy).

    It's not perfect, it won't work with domain names ending in .com.de or .org.uk, etc. but other than that I am pretty happy with it.


    Thanks for the suggestion.
     
    qwikad.com, Oct 6, 2013 IP
    bartolay13 likes this.