【问题标题】:Sub-string extraction. Get the string before last '/'子串提取。获取最后一个'/'之前的字符串
【发布时间】:2019-04-22 09:53:30
【问题描述】:

我正在尝试提取子字符串。我需要一些帮助来用 PHP 做这件事。

以下是我正在使用的一些示例字符串以及我需要的结果:

$temp = "COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"

而我需要的结果是:

$temp = d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

我想在最后一个 '/' 处获取字符串

到目前为止,我已经尝试过:

substr($temp, 0, strpos($temp, '/'))

但是,它似乎根本不起作用。

有没有办法用 PHP 方法来处理这种情况?

【问题讨论】:

  • 这是一个糟糕的问题陈述。虽然非常欢迎使用示例来说明问题,但它们应该支持对您尝试解决的问题的具体描述。您的描述有些模糊。

标签: php string substring


【解决方案1】:

您可以使用substr() 来提取数据,但使用strrpos() 来查找最后一个/ 位置(您必须删除尾随的/ 才能执行此操作)

$temp = "assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/";
// Trim off trailing / or "
$temp = rtrim($temp, "/\"");
// Return from the position of the last / (+1) to the end of the string
$temp = substr($temp, strrpos($temp, '/')+1);
echo $temp;

给...

d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

【讨论】:

    【解决方案2】:

    您可以使用 explode()end() 函数来实现。

    步骤说明:

    1) 用/ Explode() 字符串

    2) 替换双引号"

    3) array_filter() 删除空白元素。

    4) 最后一个元素 /end() 和最后一个 / 之后的空元素已被删除。

    代码:

    <?php 
    $temp = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
    $temp = str_replace('"', '', $temp);
    $url = explode('/', $temp);
    $url = array_filter($url);
    $requiredSegment = end($url);
    
    echo '<pre>';
    print_r($requiredSegment);
    echo '</pre>';
    

    输出:

    d02c25b2-5c07-11e9-8f1a-02fd8bf7d052
    

    See it live here:

    【讨论】:

      【解决方案3】:

      只需试试这段代码 sn-p

      $temp = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
      $temp = rtrim(str_replace('celc_coba/','',strstr($temp, 'celc_coba/')), "/\"")
      

      结果

      d02c25b2-5c07-11e9-8f1a-02fd8bf7d052
      

      【讨论】:

        【解决方案4】:

        你可以这样做:explode

        $str = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
        $pieces = explode("/", $str );
        

        例子

        $str = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
        
        $pieces = explode("/", $str );
        
        print_r($pieces);
        
        
        $count= count($pieces);
        
        
        echo  $pieces[$count-2];
        

        Codepad

        【讨论】:

          猜你喜欢
          • 2010-12-28
          • 2016-12-14
          • 2015-06-06
          • 1970-01-01
          • 1970-01-01
          • 2014-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多