4

我在 PHP 中运行以下代码。我的意图是在响应中获取“contact.html”,但我在输出中实际得到的是ntact.html

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

有什么想法为什么 PHP 会这样,我该怎么做才能解决这个问题?

4

5 回答 5

6

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

输出:

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

我确实意识到您正在尝试仅替换字符串开头的字符串,但如果您的字符串后面有一个http://localhost ,您可能会遇到更大的问题。

关于 ltrim 的文档:http://php.net/manual/en/function.ltrim.php Hello World 示例应该能够启发您准确地解释 ltrim 正在做什么)

ltrim 滥用的另一个例子: PHP ltrim behavior with character list

于 2017-09-22T21:57:58.997 回答
3

其他答案解释了为什么ltrim没有按照您的想法做,但可能有更好的工具来完成这项工作。

您的字符串是一个 URL。PHP 有一个内置函数可以巧妙地处理这些问题。

echo parse_url($str, PHP_URL_PATH);

parse_url确实返回带有前导斜杠的路径。如果您需要删除它,那么 ltrim就可以正常工作,因为您只会修剪一个字符。)

于 2017-09-22T22:39:46.440 回答
2

从手册上ltrim()(强调我的):

您还可以通过 character_mask 参数指定要去除的字符。只需列出您要剥离的所有字符..您可以指定一个字符范围。

这意味着您列出了一组要删除的字符,而不是单词/字符串。这是一个例子。

$str = "foo";
echo ltrim($str, "for"); // Removes everything, because it encounters an F, then two O, outputs ""
echo ltrim($str, "f"); // Removes F only, outputs "oo"
echo ltrim($str, "o"); // Removes nothing, outputs "foo"

这意味着字符掩码中列出的任何字符都将被删除。相反,您可以str_replace()通过替换http://localhost为空字符串来删除字符串的开头。

$str = 'http://localhost/contact.html';
echo $str . "<br>";
echo str_replace('http://localhost', '', $str);
于 2017-09-22T22:02:39.797 回答
1

ltrimcharacter_mask在你的情况下没有匹配项http://localhost

输出会是这样的,ntact.html 为什么?

它将匹配 http://localhost,然后/将其删除,因为它位于字符掩码中,依此类推。

为什么停下来,n因为它不在您的宪章面具中。

因此,除非字符掩码中没有匹配项,否则 ltrim 将继续删除。

$str = 'http://localhost/contact.html';
echo  ltrim($str, 'http');// output ://localhost/contact.html

在这里我将只在掩码中添加一个,/它将同时删除//

$str = 'http://localhost/contact.html';
echo  ltrim($str, 'http:/');// output localhost/contact.html
于 2017-09-22T22:37:46.930 回答
0

据我所知ltrim(),它用于从字符串的开头去除空格。请参阅文档

如果您想在http://localhost/使用substr()之后获取字符串:

$str = 'http://localhost/contact.html';
echo $str . "<br>";
echo substr($str,18); // 18 is the length + 1 of http://localhost/
于 2017-09-22T21:59:52.443 回答