Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
// 第一个函数:提取固定的一个<p>标签内容
function get_fixed_p_content($html, $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');
// 打印出 $p_nodes 变量的内容,检查是否正确检索到了<p>标签
var_dump($p_nodes);
// 设置随机数生成器的种子
mt_srand($seed);
// 创建一个数组用于存储有文本内容的<p>标签的索引
$p_with_text_indexes = [];
// 遍历所有<p>标签,将有文本内容的<p>标签的索引存储到数组中
foreach ($p_nodes as $index => $node) {
if (trim($node->nodeValue) !== '') {
$p_with_text_indexes[] = $index;
}
}
// 如果没有包含文本内容的<p>标签,则返回空字符串
if (empty($p_with_text_indexes)) {
return '';
}
// 随机选择一个包含文本内容的<p>标签进行处理
$random_index = mt_rand(0, count($p_with_text_indexes) - 1);
$random_p_index = $p_with_text_indexes[$random_index];
$random_p_node = $p_nodes->item($random_p_index);
// 获取固定的一个<p>标签内容
$fixed_p_content = $random_p_node->nodeValue;
echo "固定的<p>标签内容:$fixed_p_content<br>";
// 返回固定选择的<p>标签内的内容
return $fixed_p_content;
}
// 第二个函数:固定位置的汉字替换
function replace_fixed_hanzi($text, $seed) {
// 正则匹配汉字
$pattern = '/[\x{4e00}-\x{9fa5}]/u';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
// 如果没有找到汉字,直接返回原始文本
if (empty($matches[0])) {
return $text;
}
// 设置随机数生成器的种子
mt_srand($seed);
// 获取固定位置的汉字
$random_char_index = mt_rand(0, count($matches[0]) - 1);
$random_char_position = $matches[0][$random_char_index][1];
$random_char = $matches[0][$random_char_index][0];
// 输出将要被替换的汉字
echo "将要被替换的汉字:$random_char<br>";
// 替换固定位置的汉字
$replaced_text = substr_replace($text, '000000', $random_char_position, 3);
// 返回替换后的文本
return $replaced_text;
}
// 您提供的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 = 234;
// 调用第一个函数,提取固定的一个<p>标签内容
$p_content = get_fixed_p_content($html_text, $seed);
// 调用第二个函数,进行固定位置的汉字替换
$processed_p_content = replace_fixed_hanzi($p_content, $seed);
// 输出处理后的内容
echo $processed_p_content;
?>