Home > Back-end >  Remove www from string without affecting other parts of string
Remove www from string without affecting other parts of string

Time:03-28

I have a requirement to replace all Url prefixes from the string

Example Inputs

1)lorum ipsum www.goal.com

2)lorum ipsum http://www.goal.com

3)lorum ipsum https://www.goal.com

4)lorum ipsum https://www.goal.com/1234

5)lorum ipsum www.

Expected o/p

1)lorum ipsum goal.com

2)lorum ipsum goal.com

3)lorum ipsum goal.com

4)lorum ipsum goal.com/1234

5)lorum ipsum www.

So far i have this

function removeLinks($url) {

      //$url=preg_replace ("~^www\.~", "", $url);
      $disallowed = array('http://', 'https://','www.');
      foreach($disallowed as $d) {
            $url=str_replace($d, '', $url);

            
      }
      return $url;
   }

echo removeLinks('lorum ipsum http://www.goal.com and https://www.goal.com abd https://www.goal.com/4234234 and www.goal.com and not remove www.');

But this also remove www at the end which I don't want to be removed,any possible workaround to fix the problem

CodePudding user response:

Try this: (http[s]?:\/\/)?www\.(?=. )

Test regex here: https://regex101.com/r/fjScQn/2

CodePudding user response:

function getCleanURL($url) {
    $pattern = '#^(http(s)?://)?w{3}.#';
    if($url == 'www.') {
        return $url;
    }
    return preg_replace($pattern, '', $url);
}


echo getCleanURL('www.goal.com'); // goal.com
echo getCleanURL('http://www.goal.com'); // goal.com
echo getCleanURL('https://www.goal.com'); // goal.com
echo getCleanURL('https://www.goal.com/1234'); // goal.com
echo getCleanURL('www.'); // www.
  • Related