I have the following text, which i need it to be changing dynamically depending on a pattern replacement: (Sorry poor text)
I will be at the library (%tomorrow%), to (%borrow%) my favorite (%book%), then i will go to a ticket booking agency to (%book%) a ticket to wherever.
So i will parse it the following code:
preg_match_all('/\(%(.*?)%\)/i', $content, $matches);
if(empty($matches)) return [];
$placeholders = $matches[0];
$matchings = $matches[1];
$temp =[];
foreach ($matchings as $matching) {
$temp[] = [$matching];
}
$matchings = $temp;
$matches = [$placeholders, $matchings];
return $matches;
Which will generate the following:
array (
0 =>
array (
0 => '(%tomorrow%)',
1 => '(%borrow%)',
2 => '(%book%)',
3 => '(%book%)',
),
1 =>
array (
0 =>
array (
0 => 'tomorrow',
),
1 =>
array (
0 => 'borrow',
),
2 =>
array (
0 => 'book',
),
3 =>
array (
0 => 'book',
),
),
)
As you notice, two arrays, one for patterns, and the other for alternatives, and i have two book
words, each one has it's different meaning.
Then i store this result in DB, which i can extend alternatives, with other code. So when i update the alternatives, i have the following:
array (
0 =>
array (
0 => '(%tomorrow%)',
1 => '(%borrow%)',
2 => '(%book%)',
3 => '(%book%)',
),
1 =>
array (
0 =>
array (
0 => 'tomorrow',
1 => 'the next day',
),
1 =>
array (
0 => 'borrow',
1 => 'get',
),
2 =>
array (
0 => 'book',
1 => 'novel',
),
3 =>
array (
0 => 'book',
1 => 'buy',
),
),
)
Now i have alternatives, so i start the replacement, by searching the text (say: for (%tomorrow%)
) if exists, i will get it's index from the first array and then get the array of alternatives form the second array by (%tomorrow%)
's index, then pick one randomly.
Say i latter needed to edit the text (e.g. a post) and converted the first (%book%)
to be normal without using the pattern (will be a fixed text), so i need the second (%book%) to keep it's connection to the correct alternative's. (The verbs not the nouns)