Skip to content

Commit

Permalink
Added method generate random text
Browse files Browse the repository at this point in the history
  • Loading branch information
KorsaR-ZN committed Jun 30, 2015
1 parent 33fae48 commit e64fd49
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- Removed `__construct` from `Phalcon\Mvc\View\EngineInterface`
- Added `Phalcon\Debug\Dump::toJson()` to return an JSON string of information about a single variable
- Now instances in Phalcon\Di are built using internal optimizers instead of ReflectionClass (PHP 5.6)
- Added method `Text:dynamic()` generate random text in accordance with the template

# [2.0.3](https://github.com/phalcon/cphalcon/releases/tag/phalcon-v2.0.3) (2015-06-10)
- Added support for Behaviors in `Phalcon\Mvc\Collection`
Expand Down
32 changes: 32 additions & 0 deletions phalcon/text.zep
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,36 @@ abstract class Text

return rtrim(a, separator) . separator . ltrim(b, separator);
}

/**
* Generates random text in accordance with the template
*
* <code>
* echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hi my name is a Bob
* echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hi my name is a Jon
* echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hello my name is a Bob
* </code>
*/
public static function dynamic(string! text, string! leftDelimiter = "{", string! rightDelimiter = "}", string! separator = "|") -> string
{
if substr_count(text, leftDelimiter) !== substr_count(text, rightDelimiter) {
throw new \RuntimeException("Syntax error in string \"" . text . "\"");
}

var ld_s, rd_s, result, pattern, words;

let ld_s = preg_quote(leftDelimiter);
let rd_s = preg_quote(rightDelimiter);
let pattern = "/" . ld_s . "([^" . ld_s . rd_s . "]+)" . rd_s . "/";
let result = text;

while strpos(result, leftDelimiter) !== false {
let result = preg_replace_callback(pattern, function (matches) {
let words = explode(separator, matches[1]);
return words[array_rand(words)];
}, result);
}

return result;
}
}

0 comments on commit e64fd49

Please sign in to comment.