0

My requirement is to redirect some of my urls which contains a 8 digit number and a special character at the end.

Example urls are given below

www.example.com/anything-here/hello-12345677

www.example.com/anything-here/again-here/again-hello-12543598

www.example.com/anything-here/hello-12345677

I am using pregmatch in php to find the patterns containing "-" and 8 digit number.

I tried the below code and it is not working for me. Is my pattern correct?

$result = preg_match("#.*/-\d{8}$#i", request_uri());
Vishnu
  • 35
  • 9
  • What is the special character? I only see numbers. – chris85 Aug 03 '16 at 15:35
  • HI Chris "-" is the special character followed by 8 digit numbers. Eg: "-12345678" – Vishnu Aug 03 '16 at 15:36
  • 1
    Oh, might want to reword the `and a special character at the end`. You don't have `/-` in any of your URLs. That is why you get no matches. E.g. `-\d{8}$` would suffice for `-` then 8 numbers at the end of your string. – chris85 Aug 03 '16 at 15:37
  • So i need only -\d{8} right? – Vishnu Aug 03 '16 at 15:46
  • With the `$` other wise it is `-` and 8 numbers somewhere in the string. Also you aren't expecting `$result` to have the matched text, right? – chris85 Aug 03 '16 at 15:51
  • actually url ends with "-" and 8 digit number. But anything can come before the "-" and 8 digit number. Like anything-12345678, any-thing-12345678, any^thing-12345678 – Vishnu Aug 03 '16 at 15:58
  • Yea... thats why you need the `$`. Try what I posted. If it doesn't work update the question with your usage and what `var_dump` gives for `request_uri()`. – chris85 Aug 03 '16 at 16:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/119028/discussion-between-vishnu-and-chris85). – Vishnu Aug 03 '16 at 16:07

3 Answers3

3

The following pattern will match any URL with a dash followed by 8 digits at the end. URLs with a special character at the end would not match.

$result = preg_match("/.*-\d{8}$/i", request_uri());

Demo here:

Regex101

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

The problem with the regex you are using is that you put the pattern for the dash and eight digits directly after the forward slash, and in all the examples you showed, there are other characters between the slash and the dash.

//                                    ***** <---These chars don't match your pattern
$url = "www.example.com/anything-here/hello-12345677";
//                    .*             /     -\d{8}  $

If you want to make sure there is a slash in the url before the -\d{8}, you can add another wildcard before it (.*/.*-\d{8}$), or if it doesn't matter, then neither the slash nor the wildcard are required. (-\d{8}$).

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
-1

$result = substr(request_uri(), strpos(request_uri(), "-") + 1);

source: Get everything after a certain character

Community
  • 1
  • 1
brentg
  • 1
  • 1