从html中查找所有单词(或句子)

问题描述 投票:3回答:1

我试图找到一个html块中的所有单词。阅读manual我认为通过使用find('text')函数可以实现这一点。虽然我无法让它返回任何东西。

谁能告诉我我做错了什么?

require_once __DIR__ . '/simple_html_dom.php';

$html = str_get_html("<html><body><div><p><span>Hello to the <b>World</b></span></p><p> again</p></div></body></html>");

foreach($html->find('text') as $element) {
    echo $element->plaintext . '<br>';
}

我最终要做的是找到所有文本及其在html中的起始位置。对于这个特定的例子,它看起来像这样:

[
    0 => [
        'word' => 'Hello to the ',
        'pos' => 27
    ],
    1 => [
        'word' => 'World',
        'pos' => 43
    ],
    2 => [
        'word' => ' again',
        'pos' => 66
    ]
]

那么有人可以解释一下我在使用Simple HTML Dom做错了什么并帮我弄清楚每个单词的起始位置?或者告诉我应该使用的另一种工具?

php simple-html-dom
1个回答
-1
投票

您可以使用可用的functionstrip_tagpreg_match_all来提取每个单词的位置

$str = "<html><body><div><p><span>Hello to the <b>World</b></span></p><p> again</p></div></body></html>";
$find =  '/'.str_replace(' ','|',strip_tags($str)).'/';
preg_match_all($find, strip_tags($str), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

结果: -

 Array
(
[0] => Array
    (
        [0] => Array
            (
                [0] => Hello
                [1] => 0
            )

        [1] => Array
            (
                [0] => to
                [1] => 6
            )

        [2] => Array
            (
                [0] => the
                [1] => 9
            )

        [3] => Array
            (
                [0] => World
                [1] => 13
            )

        [4] => Array
            (
                [0] => again
                [1] => 19
            )

    )

)
© www.soinside.com 2019 - 2024. All rights reserved.