views:

39

answers:

3

I have text like this from poker software (I have highlighted the parts I need to replace).

--- FLOP --- [Jh 9h Ah]
driverseati checks
darrington has 15 seconds left to act
darrington bets 100
InvisibleEnigma calls 100
driverseati folds
--- TURN --- [Jh 9h Ah] [3c]
darrington bets 200
InvisibleEnigma calls 200
--- RIVER --- [Jh 9h Ah 3c] [Td]

Jh = Jack of hearts
9h = 9 of hearts
Ah = ace of hearts
3c = 3 of clubs

I want to replace the cards inside the square brackets with IMAGES.

So this line: --- TURN --- [Jh 9h Ah] [3c]
Needs to become: --- TURN --- jh.gif 9h.gif ah.gif 3c.gif

I can't figure out the preg_replace :( I can kind of figure it out for just a single card inside brackets (like the [3c]), but I'm stuck at replacing multiple instances on 1 line and some brackets having 3 cards and some brackets having 2, or 1 card.

This is what I have for a single card:

\[([AKQJakqj1-9]0?[DHSCdhsc])\]

Any help would be appreciated.

+1  A: 
John Kugelman
That does work, but common words like "as" will be replaced too. So I need to tell regex to just look within brackets.
Frankie Yale
Do you have to match the lowercase versions? Will those ever appear in an automated hand history?
John Kugelman
I also want to replace it in regular text (like blog posts, when a user says -- well, I was playing [ac][Kd] and lost -- meaning, playing Ace of clubs and King of Diamond). So I want to replace the pasted hand history logs as seen in the original post and user posted information.
Frankie Yale
A: 
$string = "--- RIVER --- [Jh 9h Ah 3c] [Td]";

$CARD = "[akqjt1-9][dhsc]";
echo preg_replace(
  "/\[($CARD(?:\s+$CARD){0,4})\]/ie",
  "preg_replace('/\b$CARD\b/i', '\\\$0.gif', '\$1')",
  $string);

This code outputs:

--- RIVER --- Jh.gif 9h.gif Ah.gif 3c.gif Td.gif


Looks like John (narrowly!) beat me to it while I hacked away, although my code here is a bit more specific - it won't run the replacement on any string inside brackets, like [as the world turns], it has to be a set of cards. I also limited it to 5 cards in brackets, although you could change this by simply adjusting the {0,4} in the match.

wuputah
A: 
function imageize($matches)
{
    $from = array('s','c','d','h','[',']');
    $to = array('s.gif','c.gif','d.gif','h.gif','','');
    return $matches[1] . str_replace($from, $to, strtolower($matches[2])) . $matches[3];
}

$str = preg_replace_callback('#([^\[\]]*?)((?: *\[[akqjtcsdh\d ]+\])+)([^\[\]]*?)#i', 'imageize', $str);
joebert