2017-09-22 56 views
2

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

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

有什么想法,为什么PHP是表现这种方式,我能做些什么来解决这个?

回答

4

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

0

据我所知ltrim()用于从字符串的开头剥离空格。 See documentation

如果你想利用http://localhost/后,您可以使用substr()字符串:上ltrim()(重点煤矿)

$str = 'http://localhost/contact.html'; 
echo $str . "<br>"; 
echo substr($str,18); // 18 is the length + 1 of http://localhost/ 
2

从手册:

你也可以指定你想要的字符strip,通过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); 
3

你必须使用爆炸

$str = 'http://localhost/contact.html'; 
$arr = explode('/', $str); 
echo $arr[count($arr) - 1]; 
1

LTRIM工作起来没有匹配您character_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 
2

其他答案解释为什么ltrim没有做到你认为的那样,但是这个工作可能有更好的工具。

您的字符串是一个URL。 PHP has a built-in function to handle those neatly.

echo parse_url($str, PHP_URL_PATH); 

parse_url确实有斜线返回的路径。如果您需要删除,然后ltrim会工作得很好,因为你只修剪一个字符。)