Reputation: 1
I have this code
if (preg_match('/J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if (preg_match('/BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}
I have the id
as BUTEqHLHxJSRr9DJZSMTN
, Instead of getting 2
as output, I am getting 1
.
This is has BUTEqHLHxJSRr9DJZS
MTN which is making it match with the first expression. But this exp also has BUT/TN and it should also match with that regex also right?
Is there any way I can make the regex pattern in such a way that it do not check for matches from the middle of an expression, but rather it should match the beginning and end.
I don't know whether this is a stupid question to ask,but is there anyway its possible to prevent pregmatch to match from the begining?
Upvotes: 0
Views: 392
Reputation: 70732
You can use the ^
(beginning of string), $
(end of string) anchors to match an entire string.
For example, this will give you the result of 2
seeing how it matches the entire string from start to end.
$id = 'BUTEqHLHxJSRr9DJZSMTN';
if (preg_match('/^J[a-zA-Z0-9]+S$/', $id)) { echo "1"; }
else if(preg_match('/^BUT[a-zA-Z0-9]+TN$/', $id)) { echo "2"; }
Upvotes: 3
Reputation: 13728
try ^
then it will check must be start from given string
if(preg_match('/^J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if(preg_match('/^BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}
Upvotes: 0
Reputation: 785611
Use word boundaries to avoid matching unwanted text:
if(preg_match('/\bJ[a-zA-Z0-9]+S\b/', $id)) {
echo "1";
}
else if(preg_match('/\bBUT[a-zA-Z0-9]+TN\b/', $id)) {
echo "2";
}
Upvotes: 0