user3676792
user3676792

Reputation: 23

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: [email protected]

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;

Upvotes: 2

Views: 190

Answers (7)

Rizier123
Rizier123

Reputation: 59681

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: [email protected]";

    $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] => [email protected]
)

Upvotes: 1

daxeh
daxeh

Reputation: 1085

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] => [email protected]
)

Upvotes: 0

nl-x
nl-x

Reputation: 11832

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

Upvotes: 1

Thomas Schober
Thomas Schober

Reputation: 145

In your special case use following code:

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

Upvotes: 0

Dan Bizdadea
Dan Bizdadea

Reputation: 1302

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.

Upvotes: 0

chandresh_cool
chandresh_cool

Reputation: 11830

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: [email protected]";

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

Upvotes: 0

Gnanadurai Asudoss
Gnanadurai Asudoss

Reputation: 279

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...

Upvotes: 0

Related Questions