使用php在两个字符串之间提取数据

时间:2014-05-31 21:42:36

标签: php

我想从上到下提取所有结果,我有这个脚本......

function extract_unit($string, $start, $end)
{
$pos = stripos($string, $start);

$str = substr($string, $pos);

$str_two = substr($str, strlen($start));

$second_pos = stripos($str_two, $end);

$str_three = substr($str_two, 0, $second_pos);

$unit = trim($str_three); // remove whitespaces

return $unit;
}

$result = file_get_contents('html.txt');

echo extract_unit($result,'<dd class="m_operation_In">','</dd>');
echo extract_unit($result,'<span class="Unread">','</span>');

这段代码完美无缺,但它只给了我第一个结果。我想要所有的结果。一次性中至少需要获取7-8个结果。我不知道现在该怎么办。任何形式的帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

stripos有第三个参数,您可以使用它来获取以后出现的搜索字符串。你可以循环遍历所有匹配:

function extract_unit($string, $start, $end)
{

    $offset = 0;
    $units = array();
    while(($pos = stripos($string, $start) !== false) {
        $str = substr($string, $pos, $offset);
        $str_two = substr($str, strlen($start));
        $second_pos = stripos($str_two, $end);
        $str_three = substr($str_two, 0, $second_pos);

        $units[] = trim($str_three); // remove whitespaces
        $offset = $pos + strlen($start);
    }
    return $units;
}

请注意,此方法非常脆弱 - 如果html稍有变化,此代码将会中断;你最好使用html解析器来提取这些div的内容。 http://www.php.net/manual/en/class.domdocument.php库是一个很好的起点。

修改

使用simple_html_dom,你只需使用css风格的选择器来获取你正在寻找的元素:

// Create DOM from URL or file
$html = file_get_html('https://www.pourtoi.com.au/link.txt');

// Find all m_operation_In 
foreach($html->find('dd.m_operation_In') as $element) { 
    echo $element->src . '<br>';
}

foreach($html->find('span.Unread') as $span) {
    echo $span->src . '<br/>';
}