Get a substring of a string

2019-07-23 11:22发布

问题:

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;

回答1:

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']



回答2:

This should work for you:

Here I first explode() your string by a new line character. After this I go through each element with array_map(), where I explode it again by :. Then I simply array_combine() the first array columns with the second columns, which I get with array_column().

<?php

    $str = "Username: example
            Password: pswd
            Code: 890382
            Key: 9082
            type: 1
            Website: https://example.com/example
            Email: example@example.com";

    $arr = array_map(function($v){
        return array_map("trim", explode(":", $v, 2));
    }, explode(PHP_EOL, $str));

    $arr = array_combine(array_column($arr, 0), array_column($arr, 1));

    print_r($arr);

?>

output:

Array
(
    [Username] => example
    [Password] => pswd
    [Code] => 890382
    [Key] => 9082
    [type] => 1
    [Website] => https://example.com/example
    [Email] => example@example.com
)


回答3:

Take the ending position of Username: and then find starting position of Password. Then Use these values to extract the username value. Like this find what value you want...



回答4:

Assuming your string is separated by a line break, you can try this:

$str = "Username: example

        Password: pswd

        Code: 890382

        Key: 9082

       type: 1

       Website: https://example.com/example

       Email: example@example.com";

$explode = explode("<br/>", $str);
foreach ($explode as $string) {
     $nextExplode = explode(":", $str);
         foreach($nextExplode as $nextString) {
             if ($nextString[0] == 'Code']) {
                 echo $nextString[1];
             }
          }
     }


回答5:

You can try

preg_match('/Code: ([0-9]+)/', $subject, $matches);

You should have the code in the $matches array.

You should adjust the regexp so it will fit your case. I just put an example.



回答6:

In your special case use following code:

preg_match('/Code\:\s*(.*)\s*/m', $yourstring, $match); 
$match[1] //contains your code! 


回答7:

Try doing a split delimiter "\n" and/or ':' which will then provide you an array where you can further dissect into key value pairs.

In the following example, I took the approach to read from file, and split by ":\s" given a line.

ie. example with 'data.txt'

<?php

$results = array();

$file_handle = fopen("data.txt", "r");
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $line_array = preg_split("/:\s/", $line);

   // validations ommited 
   $key = $line_array[0];
   $value = $line_array[1];

   // ie. $result['Code'] => '890382' 
   $result[$key] = $value;
}
fclose($file_handle);

print_r($result);

?>

Output Usage ie.echo $result['Username']:

Array
(
    [Username] => example

    [Password] => pswd

    [Code] => 890382

    [Key] => 9082

    [type] => 1

    [Website] => https://example.com/example

    [Email] => example@example.com
)