PHP获取句子前两词并替换主题标题报错求助
问题解决:将固定字符串替换为$titles变量提取前两词
常见错误原因及解决步骤
$titles变量未定义或无有效值
先确认$titles已正确赋值,比如从表单、数据库或其他来源获取:// 示例:从POST请求获取标题 $titles = isset($_POST['title']) ? trim($_POST['title']) : ''; // 或直接赋值测试 $titles = '前端性能优化 最佳实践指南';错误的变量替换写法
不要用<?php echo $titles; ?>这种HTML输出语法给PHP变量赋值,直接替换即可:// 错误写法: // $sentence = <?php echo $titles; ?>; // 正确写法: $sentence = $titles;边界情况容错处理
若$titles为空、只有单个词或无空格,直接拆分会报错,需增加判断:$words = explode(' ', trim($sentence)); $abbreviation = ''; if(count($words) >= 2){ $abbreviation = implode(" ", array_slice($words, 0, 2)); } elseif(count($words) == 1){ $abbreviation = $words[0]; } else { // 标题为空时设置默认值 $abbreviation = 'default keyword'; }接口请求与结果的容错处理
避免请求失败或返回格式错误导致脚本崩溃:$url = sprintf("xxx", urlencode($abbreviation)); // 捕获请求失败的情况 $json = @file_get_contents($url); if(!$json){ echo '接口请求失败'; exit; } // 转为关联数组更易处理,同时检查结果有效性 $results = json_decode($json, true); if(!is_array($results) || !isset($results[1])){ echo '无有效返回结果'; exit; }
完整修正代码
// 确保$titles有正确赋值 $titles = '前端性能优化 最佳实践指南'; // 替换为实际标题来源 $sentence = $titles; // 分词处理,增加容错 $words = explode(' ', trim($sentence)); $abbreviation = ''; if(count($words) >= 2){ $abbreviation = implode(" ", array_slice($words, 0, 2)); } elseif(count($words) == 1){ $abbreviation = $words[0]; } else { $abbreviation = 'default keyword'; } // 接口请求 $url = sprintf("xxx", urlencode($abbreviation)); $json = @file_get_contents($url); if(!$json){ echo '接口请求失败'; exit; } // 处理返回结果 $results = json_decode($json, true); if(!is_array($results) || !isset($results[1])){ echo '无有效结果'; exit; } foreach($results[1] as $result){ if(isset($result[0])){ // 转义HTML特殊字符,避免XSS风险 echo '<h2>' . htmlspecialchars($result[0]) . '</h2><br>'; } }
内容的提问来源于stack exchange,提问作者Mixat
相关产品推荐
相关产品推荐

