简体   繁体   English

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

[英]Extract data between two strings using php

I want to extract all the results from top to bottom, i have this script... 我想从上到下提取所有结果,我有这个脚本...

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>');

This code is working perfect but it is giving me only the first outcome. 这段代码可以完美地工作,但它只会给我带来第一个结果。 I want all the outcomes. 我想要所有结果。 There are at least 7-8 results that need to be fetched in a single go. 一次至少需要获取7-8个结果。 I m not sure what to do now. 我不确定现在该怎么办。 Any kind of help will be appreciated. 任何帮助将不胜感激。 Thanks 谢谢

stripos has a third parameter which you can use to fetch later occurrences of your search string. stripos具有第三个参数,您可以使用该参数来获取以后出现的搜索字符串。 You can loop through all the matches like so: 您可以像这样遍历所有匹配项:

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;
}

Note that this approach is extremely brittle - if the html changes even slightly, this code will break; 请注意,这种方法非常脆弱-如果html稍有变化,该代码就会中断; you'd be better off using an html parser to pull out the contents of these divs. 您最好使用html解析器提取这些div的内容。 The http://www.php.net/manual/en/class.domdocument.php library would be a good place to start. http://www.php.net/manual/zh/class.domdocument.php库将是一个不错的起点。

edit 编辑

Using simple_html_dom, you'll just use a css-style selector to get elements you're looking for: 使用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/>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM