我一直在尝试获取包含大约 40 行文本的字符串的子字符串。
字符串是这样的,但是带有 aprox。还有 30 行:
Username: example
Password: pswd
Code: 890382
Key: 9082
type: 1
Website: https://example.com/example
Email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42273a232f322e2702273a232f322e276c212d2f" rel="noreferrer noopener nofollow">[email protected]</a>
我需要获取例如 Code
的值,该值将为 890382
,但我似乎无法做到这一点。
每个字段(如 Code
或 Key
)在字符串中都是唯一的。最好的(如果可能的话)是读取值并将它们存储在一个数组中,该数组的位置以字段命名。如果有人能帮助我解决这个问题,我将不胜感激。
顺便说一句:这个文件托管在另一个服务器中,我只能读取该服务器,因此我无法将其更改为更像 CSV 的内容或其他内容。
我尝试使用的代码:
$begin=strpos($output, 'Code: ');
$end=strpos($output, '<br>', $begin);
$sub=substr($output, $begin, $end);
echo $sub;
最佳答案
分割每一行,然后在冒号处分割。并将 key /对放入数组中:
$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']
获取您的值
关于php - 获取字符串的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917945/