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

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.