【问题标题】:Getting variables between slash forwards in a URL获取 URL 中斜线之间的变量
【发布时间】:2019-06-23 14:27:31
【问题描述】:

假设我有一个 URL:https://somesite.com/0/posts/20/290/755653-Title.html 我如何获得这些变量:/0/, /20/, /290/?请注意,它们是变量,它们总是不同的。

我想我可以像这样得到它们:

$url = '//somesite.com/0/posts/20/290/755653-Title.html'; var_dump(parse_url($url));

但数组不会将它们显示为单独的变量。应该用preg_replace 代替吗?我不认为我知道怎么做。感谢您的帮助。

【问题讨论】:

  • 通过.htaccess?

标签: php arrays preg-replace


【解决方案1】:

一种选择是使用带有preg_match_all 的正向前瞻,您可以在其中捕获捕获组中的模式:

(?=(/\d+/))

这将匹配

  • (?=正向前瞻,断言右边是
    • (/\d+/) 匹配 /,1+ 位和 /
  • ) 关闭正向预测

Regex demo | Php demo

例如

$re = '~(?=(/\d+/))~m';
$str = 'https://somesite.com/0/posts/20/290/755653-Title.html';

preg_match_all($re, $str, $matches);
print_r($matches[1]);

结果

Array
(
    [0] => /0/
    [1] => /20/
    [2] => /290/
)

如果你想只获取数字而不需要周围的斜线,你可以只在数字周围添加组

(?=/(\d+)/) 

Php demo

【讨论】:

  • 太棒了。还有一个问题,我将如何分别回显/获取它们?例如,/20/ 将在这个数组中是什么?
  • 您的意思是要将/0/ 分别放在一个数组中吗?
  • 不,我的意思是我想像 $a、$b、$c 一样使用它们。但我不确定如何从数组中获取它们并在需要时单独使用它们。
  • @VitaliKloster 您可以通过索引访问值,例如 $a = $matches[1][0];$b = $matches[1][1];
  • 美丽。谢谢。
【解决方案2】:

您可以使用explode() 并将字符串转换为除以“/”分隔符的数组。

<?php
// Example 1
$url  = "https://somesite.com/0/posts/20/290/755653-Title.html";
$pieces = explode("/", $url);
echo $pieces[0] . "<br />";
echo $pieces[1] . "<br />";
echo $pieces[2] . "<br />";
echo $pieces[3] . "<br />";
echo $pieces[4] . "<br />";
echo $pieces[5] . "<br />";
echo $pieces[5] . "<br />";
echo $pieces[6] . "<br />";
echo $pieces[7] . "<br />";

echo "<hr />";
// Example 2
$data = "https://somesite.com/0/posts/20/290/755653-Title.html";
list($first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth) = explode("/", $url);
echo $first . "<br />";
echo $second . "<br />";
echo $third . "<br />";
echo $fourth . "<br />";
echo $fifth . "<br />";
echo $sixth . "<br />";
echo $seventh . "<br />";
echo $eighth . "<br />";

?>

输出:

https:

somesite.com
0
posts
20
20
290
755653-Title.html

https:

somesite.com
0
posts
20
290
755653-Title.html

【讨论】:

  • 我喜欢它!这就是我想要的,其实。将尝试所有这些。我从没有选择到太多! :)
  • 请注意,这实际上并没有回答原始问题。
【解决方案3】:

我们可以尝试在路径分隔符上进行拆分,然后使用 array_filter 和一个内联函数来只保留纯数字分量:

$str = 'https://somesite.com/0/posts/20/290/755653-Title.html';
$parts = explode("/", $str);
$parts = array_filter($parts, function($item) { return is_numeric($item); });
print_r($parts);

打印出来:

Array
(
    [3] => 0
    [5] => 20
    [6] => 290
)

请注意,这种方法完全避免使用正式的正则表达式,如果您需要在脚本中经常这样做,这可能会影响性能。

【讨论】:

    猜你喜欢
    • 2011-02-28
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多