Page 1 of 1
Replacing tags..
Posted: Fri Nov 22, 2013 3:51 pm
by FounderSim
So I am writing something that's like displays text, but uses its replaces certain text with its own random text conditions.
For example:
The string would be: "This '{word}' is a {something} word
where
$var['word'] = 'booze', 'smoke', 'haha'
$var['something'] = 'funny', 'not funny', 'ugly'
So I am wondering what would be the best way to find and replace the words needed with my stored variables?
Re: Replacing tags..
Posted: Fri Nov 22, 2013 4:40 pm
by requinix
preg_replace_callback() that matches on anything within {}s and looks to $var for a (random) replacement.
Code: Select all
$input = "This '{word}' is a {something} word";
$replacements = array(
"word" => array("booze", "smoke", "haha"),
"something" => array("funny", "not funny", "ugly")
);
$output = preg_replace_callback('/\{([^{}]+)\}/', function($matches) use($replacements) {
if (isset($replacements[$matches[1]])) {
return $replacements[$matches[1]][array_rand($replacements[$matches[1]])];
} else {
// what if the term isn't in the replacements list?
return $matches[0]; // unchanged
}
}, $input);
Re: Replacing tags..
Posted: Fri Nov 22, 2013 10:56 pm
by Christopher
You could also use str_replace()
Code: Select all
$str = "This '{word}' is a {something} word";
$replacements = array(
"word" => array("booze", "smoke", "haha"),
"something" => array("funny", "not funny", "ugly"),
);
$from = array();
$to = array();
foreach ($replacements as $tag => $words) {
$from[] = '{' . $tag . '}';
$wordn = rand (0 , count($words)-1 );
$to[] = $words[$wordn];
}
$str = str_replace($from, $to, $str);
Re: Replacing tags..
Posted: Sat Nov 23, 2013 12:23 am
by FounderSim
Here's what I came up with:
Code: Select all
$this->task_msg = preg_replace_callback('/\{([^{}]+)\}/',
$this->function($this->matches) $this->use($this->vars)
{
if (isset($this->vars[$this->matches[1]]))
{
return $this->vars[$this->matches[1]][$this->vars[$this->vars[$this->matches[1]]]];
}
else
{
// what if the term isn't in the replacements list?
return $this->matches[0]; // unchanged
}
},
$rec['conditionValue']
);
I am getting the error:
Parse error: syntax error, unexpected T_VARIABLE in /home2/founder/public_html/urpg.net/gamefiles/classes/task.php on line 210
Where line 210 is $this->function($this->matches) $this->use($this->vars)
I am using class files, so I added $this-> in front of the function and use because it gave me errors if I didn't.

Re: Replacing tags..
Posted: Sat Nov 23, 2013 1:44 am
by requinix
That's... not... really close to the right syntax. Can't just throw "$this->" in there like that.
Try Chris's solution. It doesn't need crazy things like callbacks and closures.