PHP报错求助:Undefined offset:1问题排查与代码修改指导
Hey there! That notice is popping up because your code is trying to access $page_title[1] when the preg_match for the title tag didn’t find a match. When preg_match fails to locate the pattern, it doesn’t populate the $page_title array with an index 1—so trying to access it triggers that undefined offset error.
Let’s break down how to fix this:
Step 1: Check if the Title Match Succeeds
First, capture the result of the preg_match that looks for the title tag. This tells us whether a match was found or not. We’ll also initialize the $page_title array to avoid any "undefined variable" warnings.
Step 2: Add a Guard Clause for the Title
Before assigning $page_title[1] to your $final_result, make sure we only do that if the match actually succeeded. If it didn’t, set a default value (like "Untitled Page") to keep your data structure consistent.
Step 3: (Optional) Improve the Title Regex
Your current regex might miss titles with extra spaces in the tag (like <title >) or uppercase tags (like <TITLE>). Adding the case-insensitive modifier (i) and allowing optional whitespace in the tag makes it more robust.
Here’s the revised code with these fixes:
$contents = file_get_contents($file); // Initialize the title array and capture the match result $page_title = []; $title_found = preg_match("/\<title\s*\>(.*?)\<\/title\>/i", $contents, $page_title); // Case-insensitive, handles whitespace if (preg_match("#\<body.*\>(.*)\<\/body\>#si", $contents, $body_content)) { // Clean up body content as before $clean_content = strip_tags($body_content[0]); $clean_content = preg_replace('/\s+/', ' ', $clean_content); $found = strpos_recursive(mb_strtolower($clean_content, 'UTF-8'), $search_term); // Only use the matched title if it exists, else use a default if ($title_found === 1) { $final_result[$file_count]['page_title'][] = $page_title[1]; } else { $final_result[$file_count]['page_title'][] = "Untitled Page"; // Or use an empty string if preferred } $final_result[$file_count]['file_name'][] = preg_replace("/^.{3}/", "\\1", $file); } for ($j = 0; $j < count($template_tokens); $j++) { if (preg_match("/\<meta\s+name=[\'|\"]" . $template_tokens[$j] . "[\'|\"]\s+content=[\'|\"](.*)[\'|\"]\>/", $contents, $res)) { $final_result[$file_count][$template_tokens[$j]] = $res[1]; } }
Why This Works
- By checking
$title_found === 1, we confirmpreg_matchfound exactly one title match, so$page_title[1]is safe to access. - The default value ensures your
$final_resultalways has apage_titleentry, even if the HTML file has no title tag. - The improved regex handles more real-world HTML cases where title tags might not be perfectly formatted.
内容的提问来源于stack exchange,提问作者Elisa Ltc

