0

Here is my PHP code,

$string = 'https://www.mydomain.lk/';
$wordlist = array("http://", "www.", "https://", "/");

foreach ($wordlist as &$word) {
    $word = '/\b' . preg_quote($word, '/') . '\b/';
}

echo $string2 = preg_replace($wordlist, '', $string);

I want to remove last "/" from $string. so i add the "/" to $wordlist array, but its not working.

can somebody help me to fix this. Thanks.

3
  • Try using a different regex delimiter. Commented Aug 26, 2013 at 4:53
  • are you just trying to get mydomain.lk from https://www.mydomain.lk/ ? Commented Aug 26, 2013 at 4:54
  • What should happen with a host like "something.domain.com"? Commented Aug 26, 2013 at 4:59

5 Answers 5

2

It seems that for the most part you wish to extract the hostname:

$host = parse_url($url, PHP_URL_HOST);

Removing the leading www. can then be done separately.

preg_replace('/^www\./', '', $host);
Sign up to request clarification or add additional context in comments.

Comments

1

You want to only replace / at the end of the string, so you need a $, like /$, but preg_quote would end up escaping the $.

The best way to remove a trailing / is using rtrim, like Sudhir suggested. Alternatively you could remove the preg_quote loop and just use regular expressions in your $wordlist:

$string = 'https://www.mydomain.lk/';
$wordlist = array("#https?://#", "#www\.#", "#/$#");

echo $string2 = preg_replace($wordlist, '', $string);

Comments

1

you could use rtrim():

$string = 'https://www.mydomain.lk/';
echo rtrim($string, '/'); //gives --> https://www.mydomain.lk

Comments

0

Try this

$url= 'https://www.mydomain.lk/';
echo $newurl = rtrim($url,"/");

Output like this format

https://www.mydomain.lk

Comments

0

Please try this:

$string = 'https://www.mydomain.lk/';
$uri = parse_url($string);
$domain = str_replace("www.", "", strtolower($uri['host']));
echo $domain;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.