【问题标题】:PHP remove characters after last occurrence of a character in a stringPHP在字符串中最后一次出现字符后删除字符
【发布时间】:2012-05-31 13:55:52
【问题描述】:

所以测试用例字符串可能是:

http://example.com/?u=ben

或者

http://example.com

我试图在最后一次出现“/”之后删除所有内容,但前提是它不属于“http://”。这可能吗!?

到目前为止我有这个:

$url = substr($url, 0, strpos( $url, '/'));

但不起作用,在第一个'/'之后剥离所有内容。

【问题讨论】:

  • 我不知道你在用这个做什么,但如果你试图去掉广告系列跟踪代码,生成的 URL 通常会起作用,但并不总是 ;-) 例如,我认为 YouTube需要“?”

标签: php substring


【解决方案1】:

实际上,一个更简单的解决方案是使用 PHP 的一些字符串操作函数。

首先,您需要找到“/”最后一次出现的位置。您可以通过使用 strrpos() 函数来做到这一点(小心,它是 2 r);

然后,如果您将此位置作为负值提供,作为 substr() 函数的第二个参数,它将从末尾开始搜索子字符串。

第二个问题是你想要最后一个'/'左侧的字符串部分。为此,您必须为 substr() 提供一个负值给第三个参数,这将指示您要删除多少个字符。

要确定需要删除多少个参数,您必须先提取“/”右侧的字符串部分,然后计算其长度。

//so given this url:
$current_url = 'http://example.com/firstslug/84'

//count how long is the part to be removed
$slug_tbr = substr($current_url, strrpos($current_url, '/')); // '/84'

$slug_length = strlen(slug_tbr); // (3)

/*get the final result by giving a negative value 
to both second and third parameters of substr() */
$back_url = substr($current_url, -strrpos($current_url, '/'), -$slug_length);

//result will be http://example.com/firstslug/

【讨论】:

    【解决方案2】:

    你必须使用 strrpos 函数而不是 strpos ;-)

    substr($url, 0, strrpos( $url, '/'));
    

    【讨论】:

    • 我认为这是对问题标题的最佳答案!如果不是为了这个答案,我会将标题编辑为“... URL 中的字符”。
    • 如果没有发现它会删除所有,对此的任何修改
    • @mokNathal 很丑但是...substr($url,0,strrpos($url,'/') !== false ? strrpos($url,'/') : strlen($url));
    • 稍微不那么难看,但是当针在第一个位置时失败:substr($url,0,strrpos($url,'/') ?: strlen($url));
    • 需要注意的是,如果没有找到你的 needle 出现,strrpos 会返回 false。如果您认为针可能不存在,请在执行此指令之前检查它是否存在。
    【解决方案3】:
    $cutoff = explode("char", $string); 
    echo $cutoff[0]; // 2 for what you want and 3 for the index
    

    还有

    echo str_replace("http://", "", $str);

    【讨论】:

    • 我觉得应该是$cutoff[1];而不是索引 0(如果我理解你的脚本)。另外,我不明白你为什么要爆炸“char”?
    • "char" = "/",至于索引0——我也写了cmets
    【解决方案4】:

    您应该使用专为此类工作设计的工具,parse_url

    url.php

    <?php
    
    $urls = array('http://example.com/foo?u=ben',
                    'http://example.com/foo/bar/?u=ben',
                    'http://example.com/foo/bar/baz?u=ben',
                    'https://foo.example.com/foo/bar/baz?u=ben',
                );
    
    
    function clean_url($url) {
        $parts = parse_url($url);
        return $parts['scheme'] . '://' . $parts['host'] . $parts['path'];
    }
    
    foreach ($urls as $url) {
        echo clean_url($url) . "\n";
    }
    

    例子:

    ·> php url.php                                                                                                 
    http://example.com/foo
    http://example.com/foo/bar/
    http://example.com/foo/bar/baz
    https://foo.example.com/foo/bar/baz
    

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2021-08-22
      相关资源
      最近更新 更多