可能的替代方案:
<?php
class Spintax
{
public function process($text)
{
preg_match_all('/(\{[^\}]+\})/', $text, $matches);
$sets = [];
foreach($matches[0] as $match) {
$sets[$match]['replacements'] = explode('|',
str_replace(
['{', '}'],
'',
$match
)
);
$sets[$match]['results'] = [];
}
foreach($sets as $placeholder => $entries) {
$replacements = $entries['replacements'];
foreach($replacements as $replace) {
$sets[$placeholder]['results'][] = str_replace(
$placeholder,
$replace,
$text
);
foreach($sets as $innerPlaceholder => $innerEntries) {
$innerResults = $innerEntries['results'];
foreach($innerResults as $result) {
$sets[$placeholder]['results'][] = str_replace(
$placeholder,
$replace,
$result
);
}
}
}
}
$output = array_unique($sets[array_key_last($sets)]['results']);
return array_values(
array_filter(
$output,
function($entry) {
return 0 === preg_match('/\{[^\}]+\}/', $entry);
}
)
);
}
}
/* EXAMPLE USAGE */
$spintax = new Spintax();
$string = '{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Davis}!';
print_r( $spintax->process($string) );
我的结果是这样的:
Array
(
[0] => Hello to you, Mr. Smith!
[1] => Howdy to you, Mr. Smith!
[2] => Hola to you, Mr. Smith!
[3] => Hello to you, Mrs. Smith!
[4] => Howdy to you, Mrs. Smith!
[5] => Hola to you, Mrs. Smith!
[6] => Hello to you, Ms. Smith!
[7] => Howdy to you, Ms. Smith!
[8] => Hola to you, Ms. Smith!
[9] => Hello to you, Mr. Williams!
[10] => Howdy to you, Mr. Williams!
[11] => Hola to you, Mr. Williams!
[12] => Hello to you, Mrs. Williams!
[13] => Howdy to you, Mrs. Williams!
[14] => Hola to you, Mrs. Williams!
[15] => Hello to you, Ms. Williams!
[16] => Howdy to you, Ms. Williams!
[17] => Hola to you, Ms. Williams!
[18] => Hello to you, Mr. Davis!
[19] => Howdy to you, Mr. Davis!
[20] => Hola to you, Mr. Davis!
[21] => Hello to you, Mrs. Davis!
[22] => Howdy to you, Mrs. Davis!
[23] => Hola to you, Mrs. Davis!
[24] => Hello to you, Ms. Davis!
[25] => Howdy to you, Ms. Davis!
[26] => Hola to you, Ms. Davis!
)