PHP实现指定区域字符串随机取词及多占位符随机文本替换问题
解决PHP中批量处理带可选竖线的随机占位符问题
Hey there! Let's tackle those two issues you're running into with your placeholder randomization code. Your current setup only handles one placeholder at a time, and trailing pipes in placeholders like {text1|text2|} cause unexpected problems. Here's a solid solution that fixes both:
$text = 'text {text1|text2|} Text3 {text4|text5}'; // Use preg_replace_callback to handle all placeholders in one pass $randomizedText = preg_replace_callback('/{(.*?)}/', function($match) { // Remove leading/trailing pipes from the placeholder content $optionString = trim($match[1], '|'); // Split into individual options $options = explode('|', $optionString); // Filter out any empty values (from consecutive pipes) $validOptions = array_filter($options); // Fallback to empty string if no valid options exist if (empty($validOptions)) { return ''; } // Pick a random option and return it $randomIndex = array_rand($validOptions); return $validOptions[$randomIndex]; }, $text); echo $randomizedText;
关键改进点:
- 批量处理多个占位符:
preg_replace_callbackautomatically finds every{...}placeholder in your string and runs the callback function on each one, so you don't have to manually handle individual matches like your original code did. - Cleanly handle trailing (or leading) pipes:
trim($match[1], '|')strips off any pipes at the start or end of the placeholder content, turningtext1|text2|intotext1|text2.array_filter($options)removes any empty entries that might come from consecutive pipes (liketext1||text2would split into['text1', '', 'text2']—this filters out the empty string).
- Fallback for empty placeholders: If a placeholder has no valid options (like
{||}), the code returns an empty string to avoid errors.
Example Output:
Running this code might output something like:
text text2 Text3 text4
Or another random combination on the next run—each placeholder gets its own independent random selection.
内容的提问来源于stack exchange,提问作者Ashik Kaiser
相关产品推荐
相关产品推荐

