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) { // 创建一个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'; foreach ($p_nodes as $node) { // 获取当前<p>标签内的文本 $text = $node->nodeValue; // 忽略script和style标签内的文本 if ($node->parentNode->nodeName !== 'script' && $node->parentNode->nodeName !== 'style' && preg_match($pattern, $text)) { if (preg_match($pattern, $text, $matches)) { // 随机选择一个汉字并替换 $random_index = array_rand($matches); $random_char = $matches[$random_index]; $text = preg_replace('/'.$random_char.'/', '000000', $text, 1); // 这里随机选择了一个"随"作为替换字符,您可以根据需要更改 $node->nodeValue = $text; break; // 替换完成后退出循环 } } } // 返回处理后的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> '; // 调用函数进行处理 $processed_html_text = replace_random_hanzi($html_text); $processed_html_text = html_entity_decode($processed_html_text); echo $processed_html_text; ?>
Show:  
Copy Clear