0

我正在构建一个小的伪装链接脚本,但我需要找到每个具有不同字符串编号的脚本,例如('mylinkname1'-1597)。顺便说一句:数字总是整数。

问题是我从不知道字符串编号,所以我想使用正则表达式,但有些东西失败了。

这是我现在得到的:

$pattern = '/-([0-9]+)/'; 

$v = $_GET['v']

if ($v == 'mylinkname1'.'-'.$pattern) {$link = 'http://example1.com/';}
if ($v == 'mylinkname2'.'-'.$pattern) {$link = 'http://example2.com/';}
if ($v == 'mylinkname3'.'-'.$pattern) {$link = 'http://example3.com/';}

header("Location: $link") ;
exit();
4

2 回答 2

1

破折号已经在模式中,因此您不必在 if 子句中添加它。

您可以省略数字周围的捕获组-[0-9]+,并且必须将模式与preg_match一起使用。

您可以将 if 语句的格式更新为:

$pattern = '-[0-9]+';

if (preg_match("/mylinkname1$pattern/", $v)) {$link = 'http://example1.com/';}

为了防止mylinkname1-1597成为更大单词的一部分,您可以用锚点包围模式^$断言字符串或单词边界的开始和结束\b

于 2019-05-27T21:51:49.013 回答
0

这里根本不需要正则表达式,只需在连字符上拆分字符串并仅匹配它,我还建议您在 3 或 if\eleses 时使用 case\switch:

$v=explode('-',$_GET['v']);

switch ($v[0]) {
    case "mylinkname1":
        $link = 'http://example1.com/';
        break;
    case "mylinkname2":
        $link = 'http://example2.com/';
        break;
    case "mylinkname3":
        $link = 'http://example3.com/';
        break;
    default:
        echo "something not right";
}

header("Location: $link") ;
exit();
于 2019-05-27T21:51:30.250 回答