php - 获取字符串的子串

标签 php string substring substr strpos

我一直在尝试获取包含大约 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,但我似乎无法做到这一点。

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

顺便说一句:这个文件托管在另一个服务器中,我只能读取该服务器,因此我无法将其更改为更像 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/

相关文章:

c# - 是否可以在不先将字符转换为自己的字符串的情况下将字符插入字符串?

sql - SQL 结果集中的字符串操作

php - 重构返回不同数据类型的函数

php - 性能方面 : Is it better to have many tiny ajax php controller scripts or one large one?

.net - 在 .NET 中查找子字符串匹配的结尾

c# - 什么时候应该使用 String.Format 或 String.Concat 而不是串联运算符?

C - 两个数组之间的 AND 运算符

MySQL 按子字符串出现次数排序

php - 如何从具有不同where条件的表中添加和减去数据

javascript - 使用 PHP 的 CORS(跨源资源共享)