Symfony爬虫使用follow-sibling获取文本

时间:2016-06-19 09:20:50

标签: symfony laravel xpath

给出以下html代码:

<div class="body">
    1. Question <strong>1</strong>
    <input type="text" />
    2. You have <u>Question</u><strong>1</strong>
    <input type="text" />
    3. Question <strong>3</strong>
    <input type="text" />
</div>

我希望得到这样的文字:

[
   0 => 'Question 1', // Or 'Question <strong>1</strong>' is better
   1 => 'You have Question 2',
   2 => 'Question 3'
]

这是我的代码:

$results = [];
$questions = $crawler->filterXPath('//*[contains(@class, "body")]/text()[normalize-space()][following-sibling::input]');
$questions = $questions->each(function($c) use (&$results) {
    $line = trim($c->text());
    if(preg_match('/^[0-9]{1,2}\./', $line, $matches) == true) {
        $number = $matches[0];
        if(is_numeric($number) && $number != '') {
            $results[] = trim(str_replace($number, '', $line));
        }
    } elseif(!empty($results)) {
        $results[count($results) - 1] .= '\n'. $line;
    }
});

return $results;

没有<strong><u>标记,它可以正常工作。你是怎么做到的?

1 个答案:

答案 0 :(得分:0)

您可以使用strip_tags($ text)从字符串中删除html

在此处阅读http://www.w3schools.com/php/func_string_strip_tags.asp

如果要删除起始编号,可以使用explode()(http://php.net/manual/en/function.explode.php),如

explode(' ', $line, 2)

注意&#34; 2&#34;最后,这将生成2个元素的数组,其中第一个是数字+点,第二个是文本。

相关问题