Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A PHP Regex Query

Tags:

regex

php

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.

like image 753
Rowan Parker Avatar asked Jun 27 '13 16:06

Rowan Parker


People also ask

What is PHP regex?

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.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.

What does Preg_match mean in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.


1 Answers

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().

like image 109
RandomSeed Avatar answered Sep 24 '22 23:09

RandomSeed