user2645118
user2645118

Reputation: 9

PHP String Replacement Not Working Properly

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.

Upvotes: 0

Views: 60

Answers (5)

Sithu
Sithu

Reputation: 4421

Please try this:

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

Upvotes: 0

Padmanathan J
Padmanathan J

Reputation: 4620

Try this

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

Output like this format

https://www.mydomain.lk

Upvotes: 0

Paul
Paul

Reputation: 141839

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);

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173562

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);

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could use rtrim():

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

Upvotes: 1

Related Questions