0

I'm building a small cloaking link script but I need to find each one with a different string number eg( 'mylinkname1'-1597). By the way: the number is always integer.

The problem is that I never know the string number so I was thinking to use regex but something is failing.

Here's what I got now:

$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();
bpy
  • 1,150
  • 10
  • 27

2 Answers2

1

The dash is already in the pattern so you don't have to add it in the if clause.

You can omit the capturing group around the digits -[0-9]+, and you have to use the pattern with preg_match.

You might update the format of the if statements to:

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

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

To prevent mylinkname1-1597 being part of a larger word, you might surround the pattern with anchors ^ and $ to assert the start and end of the string or word boundaries \b

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

no need for regular expressions here at all just split the string on the hyphen and only match that, also I recommend a case\switch when you 3 or if\eleses:

$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();