I've only just been trying to teach myself how to use regular expressions so sorry if this seems trivial to some.
I'm making a little crib script. It uses a standard deck of playing cards and I'm using CDHS
(clubs, diamonds, hearts, spades) for suits and A2..9TJQK
(ace, 2...9, 10, jack, queen, king) for the ranks.
I have variable $hand
which is an even-length string of cards. For example, S2HA3D
would be the 2 of spades, ace of hearts and 3 of diamonds respectively. Note the suit and rank can be either way round.
I'm using:
preg_match_all("/[2-9ATJQK][CDHS]|[CDHS][2-9ATJQK]/i", $hand, $result);
to find all the cards but this returns suits and ranks in the order found.
My question is how can I make the result give the rank first for each card, regardless of the order given. I hope I've worded this clearly.
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
Definition and Usage The preg_match() function returns whether a match was found in a string.
I don't think you can do that with preg_match
only.
This function is meant to match strings, not manipulate them. You can, however, do a preg_replace
in a second pass:
preg_match_all("/[2-9ATJQK][CDHS]|[CDHS][2-9ATJQK]/i", $hand, $rawResult);
$normalisedResult = preg_replace('/([CDHS])([2-9ATJQK])/i', "$2$1", $rawResult[0]);
In case you wonder, $1
and $2
are backreferences to the groups identified by the parenthesis in the first argument of preg_replace()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With