获取字符串的子串 [英] Get a substring of a string

查看:48
本文介绍了获取字符串的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试获取包含大约 40 行文本的字符串的子字符串.

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

字符串是这样的,但带有 aprox.还有 30 行:

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

我需要获取例如 Code 的值,即 890382,但我似乎无法做到.

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

CodeKey 等每个字段在字符串中都是唯一的.最好的(如果可能的话)是读取这些值并将它们存储在一个以字段命名的位置的数组中.如果有人能帮我解决这个问题,我将不胜感激.

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.

顺便说一句:此文件托管在另一台服务器中,我只能访问该服务器,因此我无法将其更改为更像 CSV 之类的内容.

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.

我尝试使用的代码:

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

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

推荐答案

分割每一行,然后在冒号处分割.并将密钥/对放入一个数组中:

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

现在您可以通过访问 $values['Code']

这篇关于获取字符串的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆