Jump to content

Replacing with multiple arrays


vezquex

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/45834-replacing-with-multiple-arrays/
Share on other sites

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);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.