PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php function replace_random_hanzi($html, $seed) { // 设置随机数生成器的种子 mt_srand($seed); // 创建一个DOMDocument对象并加载HTML $dom = new DOMDocument(); @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); // 创建一个DOMXPath对象 $xpath = new DOMXPath($dom); // 获取所有<p>标签 $p_nodes = $xpath->query('//p'); // 正则匹配汉字 $pattern = '/[\x{4e00}-\x{9fa5}]/u'; // 从所有<p>标签中随机选择一个进行处理 $random_index = mt_rand(0, $p_nodes->length - 1); $random_p_node = $p_nodes->item($random_index); // 获取随机选择的<p>标签内的文本 $text = $random_p_node->nodeValue; // 查找所有汉字的位置 preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE); // 如果没有找到汉字,直接返回原始HTML if (empty($matches[0])) { return $dom->saveHTML(); } // 随机选择一个汉字的位置 $random_char_index = mt_rand(0, count($matches[0]) - 1); $random_char_position = $matches[0][$random_char_index][1]; // 替换随机选择的汉字 $text = substr_replace($text, '000000', $random_char_position, 3); // 这里固定替换为"000000",您可以根据需要更改 $random_p_node->nodeValue = $text; // 返回处理后的HTML return $dom->saveHTML(); } // 您提供的HTML文本 $html_text = ' <p style="text-align:center;"><img src="/wp-content/img/2024/03/2024030987fd1d897.jpg"/></p> <p><strong>【比赛关键事件】</strong></p> <p><strong>第10分钟,加纳乔禁区左侧扣球变向被塔尔科夫斯基绊倒,裁判果断判罚点球。↓</strong></p> <p><strong>B费主罚点球一蹴而就,曼联1-0埃弗顿!↓</strong></p> <p><strong>两度造点!第35分钟,加纳乔中路凭借个人能力突破,杀入禁区被戈弗雷放倒,裁判再次判罚点球。↓</strong></p> '; // 设置种子值 $seed = 12345; // 调用函数进行处理 $processed_html_text = replace_random_hanzi($html_text, $seed); $processed_html_text = html_entity_decode($processed_html_text); echo $processed_html_text; ?>
Show:  
Copy Clear