Var*_*rma 2 php url substring url-parsing texttrimming
我在 PHP 中运行以下代码。我的目的是在响应中获得“contact.html”,但我在输出中实际得到的是ntact.html
$str = 'http://localhost/contact.html';
echo $str . "<br>";
echo ltrim($str,'http://localhost');
Run Code Online (Sandbox Code Playgroud)
有什么想法为什么 PHP 会这样,我该怎么做才能解决这个问题?
ltrim不会做你认为它会做的事情。它使用字符集合,因此删除其中的所有字符。您应该使用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);
Run Code Online (Sandbox Code Playgroud)
输出:
http://localhost/contact.html
contact.html
Run Code Online (Sandbox Code Playgroud)
我确实意识到您正在尝试仅替换字符串开头的字符串,但是如果您的字符串后面有http://localhost,您可能会遇到更大的问题。
关于 ltrim 的文档:http ://php.net/manual/en/function.ltrim.php (Hello World 示例应该对解释 ltrim 正在做什么有启发性)
ltrim 误用的另一个例子: PHP ltrim 行为与字符列表