2

I want to match a URL on my 404 page and based on that I want to redirect user to particular location.

The URL is http://domain.com/there/12345

// example: /there/12345
$request = $_SERVER['REQUEST_URI'];

if (preg_match('', $request)) {

}

What REGEX I should put to get this? And once the test is successful, how can I retrieve this ID (12345) right after constant there?

1

5 Answers 5

3

The regexp you want to use is:

$str=$_SERVER['REQUEST_URI'];   
$regex = '/\/there\/(\d+)/';
$matches=array();
preg_match($regex, $str, $matches);
var_dump($matches)

This gives

array
  0 => string '/there/12345' (length=12)
  1 => string '12345' (length=5)

Notice the parantheses around \d+ capture anything that \d+ matches (i.e. continuous string of digits 0-9)

If you want to have a hexadecimal id (like 12ABF) then you should change the \d+ to [a-zA-Z\d]+

Sign up to request clarification or add additional context in comments.

2 Comments

The good thing with this solution is you put [a-zA-Z\d]+ and saved me going into comment cycle!
[a-fA-F\d]+ would be better for validation hexadecimal
2

You can also use basename function.

$path = "http://domain.com/there/12345";
$filename = basename($path);  
echo $filename; // Sholud be 12345

3 Comments

That's neat, I must try and remember this one.
This does nothing to ensure matching of the /there/ string component. Still, basename is highly convenient if getting 12345 is the only goal for this question.
@macek YES, You are right. This function will returns trailing name component of path.
1

This should do what you need:

$request = $_SERVER['REQUEST_URI'];
$match = array();
if (preg_match('@^/there/(\d+)$@', $request, $match)) {
    $id = $match[1];
    // Do your processing here.
}

Comments

1

Or if you tend to forget the \d syntax, and want to avoid the @ symbol or / as a delimiter:

$request = '/there/12345';

if (preg_match('#/there/([0-9]+)#', $request, $match)) {
    $id = $match[1];
    echo "ID: $id";
}

Comments

1

This will work :)

if(preg_match('#^/there/(\d+)$#', $request, $matches)){
  echo "the id is {$matches[1]}";
}
else {
  echo "no match!";
}

See it work here

Explanation

#          delimiter
^          beginning of string
/there/    string literal '/there/'
(          begin capture group 1
  \d+      one or more [0-9]
)          end capture group 1
$          end of string
#          delimiter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.