vezquex Posted April 6, 2007 Share Posted April 6, 2007 So I have a script for a play. A character's line starts with a capital letter ($CharAbbr), a colon, and a space. I want to replace this with a span tag including a the character's color class ($CharColor) and their full name ($Char). Here's what I have: <?php $AllPosts = " <br />M: Hello. <br />V: 'Tsup? "; $Char = array("Victor", "Mike"); $CharAbbr = array("V","M"); $CharAbbrXOR = implode("|", $CharAbbr); $CharColor = array("red","blue"); function combine($keys,$vals) { $combined = array(); for($i = 0; $i < count($keys); ++$i) $combined[$keys[$i]] = $vals[$i]; return $combined; } $CharAndAbbr = combine($CharAbbr,$Char); $CharAbbrAndColor = combine($CharAbbr,$CharColor); $AllPosts = preg_replace("/($CharAbbrXOR): /" , "<span class=\"char ".$CharAbbrAndColors["$1"]."\">".$CharsAndAbbr["$1"]."$1</span>" , $AllPosts); echo $AllPosts; ?> Where did I go wrong? Quote Link to comment Share on other sites More sharing options...
effigy Posted April 6, 2007 Share Posted April 6, 2007 I would use a callback; otherwise, you have to use the /e modifier and change the syntax in order to have the array values interpolated after the match. <?php $AllPosts = " <br />M: Hello. <br />V: 'Tsup? "; $Char = array("Victor", "Mike"); $CharAbbr = array("V","M"); $CharColor = array("red","blue"); function combine($keys, $vals) { $combined = array(); $size = count($keys); for ($i = 0; $i < $size; $i++) { $combined[$keys[$i]] = $vals[$i]; } return $combined; } $CharAndAbbr = combine($CharAbbr,$Char); $CharAbbrAndColor = combine($CharAbbr,$CharColor); function format_name ($matches) { $initial = $matches[1]; global $CharAbbr, $CharAndAbbr, $CharAbbrAndColor; // Format existing character. if (in_array($initial, $CharAbbr)) { return '<span class="' . $CharAbbrAndColor[$initial] . '">' . $CharAndAbbr[$initial] . '</span>'; } // Character does not exist, return what was found. return $matches[0]; } echo $AllPosts = preg_replace_callback('/([A-Z]): /', 'format_name', $AllPosts); ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.