【问题标题】:How get the end of string in php?如何在php中获取字符串的结尾?
【发布时间】:2017-12-01 12:11:55
【问题描述】:

Substr PHP

我有一个string 像这样的http://domain.sf/app_local.php/foo/bar/33。 最后一个字符是元素的id。他的长度可能不止一个,所以我不能使用:

substr($dynamicstring, -1);

在这种情况下必须是

substr($dynamicstring, -2);

如何在不依赖长度的情况下获取string 上“/bar/”之后的字符?

【问题讨论】:

标签: php substring


【解决方案1】:

为确保您在小节之后立即获得部分,请使用正则表达式:

preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33

【讨论】:

  • 这里很容易成为最佳解决方案,其他都忽略了获取数据的可能性或对ID进行假设。
  • 我需要初始化$matches 吗?我得到$matches = {array}[0] 所以它对我不起作用......我做错了什么?
  • 你不需要初始化它。你在做this以外的事情吗? @奥斯卡
【解决方案2】:

你可以使用explode,像这样:

$id = explode('/',$var);

并获取您拥有 id 的元素。

【讨论】:

  • 和 Luke Taylor 的回答一样,这行不通,因为 end 期待的是一个参考,而不是一个值。
  • 是的,这可能是一个解决方案。但这不可能得到GET 的值。我不需要GET 值,所以我会使用这个解决方案
  • $id 是一个数组,所以我在$id[1] 中有我的价值,谢谢@Eduardo Gabaldón
【解决方案3】:

您可以使用explode('/',$dynamicstring) 将字符串拆分为每个/ 之间的字符串数组。然后你可以在这个结果上使用end() 来得到最后一部分。

$id = end(explode('/',$dynamicstring));

希望这会有所帮助!

【讨论】:

  • 这行不通,因为 end 需要一个数组作为参考。
  • @omerowitz 它有效,它也只是触发一个通知。 explode 的返回值应该在传递给 end 之前定义为一个中间变量以避免这种情况。
  • 正如我在回答中所做并解释的那样。
  • 我有下一个输出尝试你的答案:Only variables should be passed by reference 但是,是的,它有帮助。我可以使用explode然后得到数组的结尾,但忽略GET数据的可能性
【解决方案4】:

试试这个:

$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';

// split your string into an array with /
$parts = explode('/', $dynamicstring);

// move the array pointer to the end
end($parts);

// return the current position/value of the $parts array
$id = current($parts);

// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);

echo $id;
// $id => 33

测试它yourself here

【讨论】:

    【解决方案5】:

    你可以使用正则表达式来做到这一点:

    $dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
    if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
        echo $m[1];
    }
    

    【讨论】:

      【解决方案6】:

      在回答之前我自己测试过了。其他答案也很合理,但这将根据您的需要起作用..

      <?php
      $url = "http://domain.sf/app_local.php/foo/bar/33";
      $id = substr($url, strpos($url, "/bar/") + 5);    
      echo $id;
      

      【讨论】:

      • 那么当他的33变成33063时,OP应该怎么做?
      【解决方案7】:

      请在下面找到答案。

      $str = "http://domain.sf/app_local.php/foo/bar/33";
      $splitArr = explode('/',explode('//',$str)[1]);
      var_dump($splitArr[count($splitArr)-1]);
      

      希望这会有所帮助。

      【讨论】:

      • 如果应该避免长度,为什么 OP 应该使用计数?
      • 我最亲爱的主...出于什么原因,您先爆炸/,然后爆炸//,然后在第二次爆炸后获得其余部分...然后count - 1?当我只提供一个路径名而不是完整的 URL 时,会发生什么?
      猜你喜欢
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多