简体   繁体   中英

How to find the second string between two strings

I have been working on a script that pulls information from a certain website. The said website pulls the information from a database and displays it in a way the user can easily read it (like always).

Imagine it looks like this:

Var1 : result1 Var2: result2 Var3: result3

What my script does is that it reads the page's source code and retrieves "result1", "result2" and "result3" by obtaining the text between two strings.

Sample code:

<?php

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

        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);

    }

    function check($url) {

        // usually, $fullstring = file_get_contents($url);
        $fullstring = "<string1>result1</string1><string1>result2</string1><string1>result3</string1>";

        $result = get_string_between($fullstring, "<string1>", "</string1>");

        echo "<b>Result: </b>".$result;

    }

    check("random");    // just to execute the function

?>

In case you wonder why I have the check() function there it is because this code is part of something bigger and I need a solution that works in this case scenario, so I tried to keep it immaculate.

Now, I can easily get "result1" because it's the first occurrence, but how can I get "result2" and "result3"?

Thank you :)

Use a regex to extract all of the matches, then pick the ones you want:

function get_string_between($string, $start, $end) 
{
    preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
    return $matches[1];
}

The regex will capture anything between the $start and $end variables.

Now the function returns an array of all of the result values, which you can pick which one you want:

list( $first, $second, $third) = get_string_between( $string,  "<string1>", "</string1>");

You can see it working in this demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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