You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_callback automatically 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, turning text1|text2| into text1|text2.
    • array_filter($options) removes any empty entries that might come from consecutive pipes (like text1||text2 would 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:15:50