You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用simple_html_dom.php解析时如何提取<h1>标签中的第二个单词?

解决simple_html_dom提取h1文本第二个单词的问题

你的核心问题是没有获取到h1元素的纯文本内容,直接对元素对象进行字符串操作时,它会输出整个标签的HTML代码,导致结果不符合预期。以下是修正方案:

错误原因分析

原代码中$town = $html->find('h1.entry-title', 0);得到的是simple_html_dom的元素对象,直接赋值给$town_name后,对其执行stripos或substr时,PHP会自动将对象转换为该元素的完整HTML字符串(即<h1 class="entry-title">Taxi Barcelona</h1>),所以你的截取操作是基于整个标签代码,而非文本内容。

正确实现方法

方法1:通过分割字符串提取

利用explode按空格分割纯文本,直接取第二个元素:

// 获取h1元素
$town = $html->find('h1.entry-title', 0);
// 提取元素的纯文本内容
$town_text = $town->plaintext;
// 去除首尾空白后按空格分割成数组
$word_list = explode(' ', trim($town_text));
// 取第二个单词(数组索引从0开始)
$town_name = $word_list[1];
echo $town_name; // 输出:Barcelona

方法2:通过字符串截取提取

找到第一个空格的位置,从该位置后开始截取:

$town = $html->find('h1.entry-title', 0);
$town_text = $town->plaintext;
// 定位第一个空格的位置
$space_position = strpos($town_text, ' ');
// 从空格后一位开始截取到末尾
$town_name = substr($town_text, $space_position + 1);
echo $town_name; // 输出:Barcelona

内容的提问来源于stack exchange,提问作者Nafis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 10:24:45