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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With