Reputation: 1601
I am struggling to match for a phrase with an if char exists regex query. What I want to be able to do is scan this string:
teamplayerID=5432&groupplayerID=2345
and only get out teamplayerID=5432
. Sometimes &groupplayerID exists and sometimes not.
I have tried:
/teamplayerID=(.*)(&?)/
over at https://regex101.com/r/QmMUkm/1
However that code above seems to select the entire string,
How do I get the regex to stop if it detects an &
and only get what I want but also select what I want even if no &
exists.
Upvotes: 0
Views: 49
Reputation: 23958
If Teamplayer is always a number you can use \d+
teamplayerID=(\d+)
https://regex101.com/r/xj1WNN/1
If it's not always a number you can use \w+ which will match both numbers and letters.
teamplayerID=(\w+)
https://regex101.com/r/xj1WNN/1
$str = "teamplayerID=54";
$pos1 = strpos($str, "=")+1;
$pos2 = strpos($str, "&", $pos1);
if($pos2 == 0) $pos2 = strlen($str);
echo substr($str, $pos1, $pos2-$pos1);
Find =
save as pos1.
Find &
after =
and save as pos2.
If there is no &
use strlen($str) as pos2.
Substring pos1 and lenght (pos2-pos1).
EDIT; Forgot about the groupID not always being there.
Upvotes: 0
Reputation: 626747
You need to use a [^&]*
negated character class:
teamplayerID=([^&]*)
See the regex demo
The [^&]*
pattern matches 0 or more occurrences of characters other than &
.
If the ID is always a group of digits, just use \d*
(0+ digits) instead, teamplayerID=(\d*)
.
Upvotes: 3