0

我正在尝试编写一个脚本,以在留言板上记录投票中的 IP,只有在我们的一项投票中进行投票时才会触发该脚本。编辑:我通过网络信标进行此操作,因为我无权访问民意调查的程序。/编辑

当脚本启动时,它需要知道正在对哪个投票进行投票,因为通常同时打开多个投票,并将投票者的 IP 记录在专用于该投票的平面文件中。

首先,我获取引用 URL,其格式如下:

http://subdomain.sample.com/t12345,action=vote

如果在引用 URL 中找到“投票”,我要做的下一件事就是获取该 t# 并将其转换为变量,这样我就可以将信息记录到名为 t12345.txt 或 12345.txt 的文件中,或者没关系,只要它与投票的主题编号匹配即可。

/t 后面的数字是该 URL 中唯一应该更改的内容。目前这里有 5 位数字,我预计这不会很快改变。

我的问题是:如何从 URL 中获取这个 t# 并从中创建一个变量?

先感谢您!

4

4 回答 4

1

查看preg_match

preg_match('|/t[0-9]{5}|', $url, $matches);
if (count($matches)) {
    $t_number = $matches[0]; // "/t12345"
    $number = substr($t_number, 2, strlen($t_number)); // 12345
}

假设:

1) 引用 url 永远不会有 t##### 模式。(t12345.com/vote)

2) 你总是有五位数。(如果这种情况发生变化,您可以执行 {5,6} 以匹配 5-6 个实例

于 2013-06-16T00:49:57.470 回答
1

柯蒂斯已经回答了,但这里有一个非正则表达式的替代方案:

  1. 在 URL 上使用parse_url来获取“路径”。
  2. 使用带逗号分隔符的explode将您的 t# 作为结果中的数组元素 0。
  3. (可选)对来自 2 的结果的元素 1 使用 explode 并使用 = 分隔符在元素 0 中获取“动作”并在此新结果的元素 1 中获取“投票”。

例如。

$url = "http://subdomain.sample.com/t12345,action=vote";
$url_pieces = parse_url($url);
$path = str_replace("/","",$url_pieces["path"]);
$args = explode(',',$path);

t_number_thingy = $args[0];

编辑:添加 str_replace 因为 parse_url 将在路径上包含斜杠。

于 2013-06-16T00:50:46.803 回答
0

你不需要使用正则表达式,你也可以使用str_replace(); 基本名称();

喜欢:

<?php
$ref = "http://subdomain.sample.com/t12345,action=vote";

if(substr($ref,-4)==="vote"){
    $ref = basename(str_replace(',action=vote','',$ref));
}

echo $ref; //t12345
?>

或者一个班轮:

$ref = (substr($ref,-4)==="vote") ? basename(str_replace(',action=vote','',$ref)) : "Unknown"; 
于 2013-06-16T01:09:25.137 回答
0

非正则表达式解决方案(不知道性能),可能有更好的方法,但它有效。

<?php

$var = "http://subdomain.sample.com/t12345,action=vote;";
$remove = "http://subdomain.sample.com/t";
$intCount = 5;

echo substr($var, strpos($var, $remove) + strlen($remove), $intCount);

?>

phpFiddle

于 2013-06-16T00:50:44.140 回答