If:
- the four city placeholders that are randomly selected should not repeat within your 3-sentence string and
- you don't mind mutating the input array and
- you will always have enough values to accommodate all of the placeholders, then:
You can pass the array into the custom function scope as a reference variable. This means that as you access and remove values via array_pop()
, it will be impossible to encounter the same city twice. You only need to shuffle()
the input array once before performing the replacements.
Code: (Demo)
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time.";
$keyword = "[city]";
$values = ["Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"];
shuffle($values);
echo preg_replace_callback(
'/' . preg_quote($keyword) . '/',
function() use(&$values) { return array_pop($values); },
$text
);
Potential outputs:
Welcome to Detroit. I want Tampa to be a random version each time. Dallas should not be the same Orlando each time.
or
Welcome to Orlando. I want Miami to be a random version each time. Atlanta should not be the same Detroit each time.
or
Welcome to Atlanta. I want Tampa to be a random version each time. Orlando should not be the same Dallas each time.
etc.
Obeying the same rules as initially described at the top of this answer, it will be easier to read and maintain an approach which does not leverage regex. Simply shuffle the array, replace the square-brace placeholders with placeholders that the printf()
family if functions can recognize, then feed the entire shuffled array to vprintf()
.
This has the added benefit of not mutating/consuming the original array via array_pop()
. (Demo)
shuffle($values);
vprintf(
str_replace(
$keyword,
'%s',
$text
),
$values
);