【问题标题】:Get number from an url in PHP从 PHP 中的 url 获取数字
【发布时间】:2014-05-27 10:08:05
【问题描述】:

我有以下网址:http:example.com/country/France/45。 使用模式http:example.com/country/name/**NUMBER**(?$_GET possibly)

如何使用正则表达式(或其他的正则表达式)提取数字?

【问题讨论】:

  • \/country\/.*\/([0-9]+) 用 preg_match_all 试试这个

标签: php regex


【解决方案1】:

使用正则表达式:

$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);

【讨论】:

    【解决方案2】:
    $url = 'http:example.com/country/France/45';
    $id  = end(explode('/',trim($url,'/')));
    

    简单不?

    trim ()的用法是去掉尾随的\

    【讨论】:

      【解决方案3】:
      echo $last = substr(strrchr($url, "/"), 1 );
      

      strrchr() 将给出/ 字符的最后一次出现,然后substr() 在它之后给出字符串。

      【讨论】:

        【解决方案4】:

        使用类似的东西

            $url = "http://example.com/country/France/45";
            $parts = explode('/', $url);
            $number = $parts[count($parts) - 1];
        

        如果你最后有 GET 变量,你可以像这样进一步爆炸

            $number = explode('?', $number);
            $number = $number[0];
        

        希望这会有所帮助:)

        【讨论】:

          【解决方案5】:

          php 的 get 命令是 $_GET 以便显示给数字 do

          <html>
          <body>
          <?php
          echo $_GET["eg"];
          ?>
          </body>
          </html>
          

          网址为http:example.com/country/name/?eg=**NUMBER**

          【讨论】:

            【解决方案6】:

            使用explode():

            $parts = explode('/', $url);
            $number = $parts[count($parts)-1];
            

            【讨论】:

            • 如果没有get参数并且url不以/结尾,这将失败!
            • 我想你想说 $number = $parts[count($parts)-1]
            猜你喜欢
            • 2011-03-18
            • 2018-09-05
            • 1970-01-01
            • 2015-02-08
            • 2017-06-03
            • 2014-01-14
            • 1970-01-01
            • 1970-01-01
            • 2016-08-06
            相关资源
            最近更新 更多