问题
I've been searching for hours trying to find a solution to this. I am trying to determing if the REQUEST URI is legit and break it down from there.
$samplerequesturi = "/variable/12345678910";
To determine if it is legit, the first section variable
is only letters and is variable in length. The second section is numbers, which should have 11 total. My problem is escaping the forward slash so it is matched in the uri. I've tried:
preg_match("/^[\/]{1}[a-z][\/]{1}[0-9]{11}+$/", $samplerequesturi)
preg_match("/^[\\/]{1}[a-z][\\/]{1}[0-9]{11}+$/", $samplerequesturi)
preg_match("/^#/#{1}[a-z]#/#{1}[0-9]{11}+$/", $samplerequesturi)
preg_match("/^|/|{1}[a-z]|/|{1}[0-9]{11}+$/", $samplerequesturi)
Among others which I can't remember now.
The request usually errors out:
preg_match(): Unknown modifier '|'
preg_match(): Unknown modifier '#'
preg_match(): Unknown modifier '['
Edit: I guess I should state that the REQUEST URI is already known. I'm trying to prove the whole string to make sure it isn't a bogus string ie to make sure there the 1st set is only lower case letters, and the 2nd set is only 11 numbers.
回答1:
/
is not the only thing you can use as a delimiter. In fact, you can use almost any non-slphanumeric character. Personally I like to use ()
because it reminds me that the first item of the result array is the entire match and it also never needs escaping in the pattern.
preg_match("(^/([a-z]+)/(\d+)$)i",$samplerequesturi,$out);
var_dump($out);
That should do it.
回答2:
Your problem may be that you are using the /
forward-slash as a regex delimiter (at the start and end of the regex expression). Switch to using a character other than the forward-slash, such as a #
hash symbol or any other symbol which will never need to appear in this particular expression. Then you won't need to escape the forward-slash character at all in the expression.
回答3:
If you want to use regex (which I don't think is necessary in this case, simply splitting on "/" should be fine:
$samplerequesturi = "/variable/12345678910";
preg_match("@^/([A-Za-z]+)/(\d+)$@", $samplerequesturi, $out);
echo $out[1];
echo $out[2];
should get you going
来源:https://stackoverflow.com/questions/12239424/trying-to-find-forward-slash-in-preg-match