Search code examples
phpstringsubstringsubstrstrpos

Get a substring of a string


I've been trying to get a substring of a string that contains around 40 lines of text.

The string is something like this but with aprox. 30 more lines:

Username: example
Password: pswd
Code: 890382
Key: 9082
type: 1
Website: https://example.com/example
Email: example@example.com

I need to get the value of, for example, Code which will be 890382, but I can't seem to do it.

Each field like Code or Key is unique in the string. The best (if possible) would be to read the values and store them in an array with positions named after the fields. If someone could help me with this I would be grateful.

BTW: This file is hosted in a different server which I only have access to read so i can't change it into something more CSV like or something.

Code i've tried to use:

$begin=strpos($output, 'Code: ');
$end=strpos($output, '<br>', $begin);

$sub=substr($output, $begin, $end);
echo $sub;

Solution

  • Split each line, and then split on the colon sign. And put the key/pairs into an array:

    $string = "..."; // your string
    $lines = explode("\n",str_replace("\r","\n",$string)); // all forms of new lines
    foreach ($lines as $line) {
        $pieces = explode(":", $line, 2); // allows the extra colon URLs
        if (count($pieces) == 2) { // skip empty and malformed lines
            $values[trim($pieces[0])] = trim($pieces[1]); // puts keys and values in array
        }
    }
    

    Now you can get your value by accessing $values['Code']