Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the protocol and domain from a url string?

I am running the following code in PHP. My intention is to get "contact.html" in the response, but what I actually get in the output is ntact.html

$str = 'http://localhost/contact.html';
echo $str . "<br>";
echo ltrim($str,'http://localhost');

Any thoughts why PHP is behaving this way and what can I do to fix this?

like image 963
Varun Verma Avatar asked Sep 15 '25 11:09

Varun Verma


2 Answers

ltrim doesn't do what you think it does. It uses a character collection, so all characters within are deleted. You should delete the substring using str_replace.

http://php.net/manual/en/function.str-replace.php

$str = 'http://localhost/contact.html';
echo $str . "<br>";
echo str_replace('http://localhost/', '', $str);

Output:

http://localhost/contact.html
contact.html

I do realize that you're trying to only replace a string that's at the beginning of your string, but if you have an http://localhost later in your string, you might have bigger problems.

Documentation on ltrim: http://php.net/manual/en/function.ltrim.php (The Hello World example should be enlightening on explaining exactly what ltrim is doing)

Another example of ltrim misuse: PHP ltrim behavior with character list

like image 67
Kwahn Avatar answered Sep 17 '25 03:09

Kwahn


Other answers explain why ltrim isn't doing what you thought it would, but there's probably a better tool for this job.

Your string is a URL. PHP has a built-in function to handle those neatly.

echo parse_url($str, PHP_URL_PATH);

(parse_url does return the path with a leading slash. If you need to remove that, then ltrim will work just fine since you'll only trimming one character.)

like image 43
Don't Panic Avatar answered Sep 17 '25 02:09

Don't Panic