【问题标题】:How to remove the protocol and domain from a url string?如何从 url 字符串中删除协议和域?
【发布时间】:2018-03-04 13:32:09
【问题描述】:

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

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

有什么想法为什么 PHP 会这样,我可以做些什么来解决这个问题?

【问题讨论】:

标签: php url substring url-parsing texttrimming


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    据我所知ltrim() 用于去除字符串开头的空格。 See documentation.

    如果你想取http://localhost/之后的字符串你可以使用substr():

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

    【讨论】:

      【解决方案3】:

      来自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"
      

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

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

      【讨论】:

        【解决方案4】:

        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
        

        【讨论】:

          【解决方案5】:

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

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

          echo parse_url($str, PHP_URL_PATH);
          

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-03-04
            • 2023-03-20
            • 2018-06-02
            • 1970-01-01
            • 2014-03-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多