regex失败,没有任何错误


regex failing with no errors

我在一个名为$test的字符串中有以下文本:

Content-Type: text/plain
Server: testapp (4.2.1 (x86_64/linux))
Content-Length: 125
{"password":"123","email_address":"","name":"j.doe","username":"jd123"}

我正在尝试用php编写一个正则表达式,它将返回内容长度为125之后的所有内容。到目前为止,我拥有的是:

if (preg_match('/^Content'-Length':[0-9''n]+([a-zA-Z0-9'{'}'"':])*/',$test,$result))
{
         var_dump($result[1]);
} 

我没有收到任何错误消息,但它找不到我在字符串中定义的模式。我也尝试过这种模式:

  '/^Content'-Length':[0-9''n]+([a-zA-Z0-9{}'"':])*/'

我试图删除大括号前面的转义符。但这仍然是不可能的。

你能告诉我我缺了什么吗?谢谢

编辑1

我的代码现在看起来是这样的:

<?php
$test = "Content-Type: text/plain
Server: kamailio (4.2.1 (x86_64/linux))
Content-Length: 125
{"password":"test123","email_address":"","name":"j.doe","username":"jd123"}";
//if (preg_match('/Content-Length':[0-9''n]*([a-zA-Z0-9{}'"':])*/',$test,$result))
//{      
//         var_dump($result);
//}
preg_match('/({.*})/', $str, $matches);
echo $matches[0];
?>

这给了我以下错误:

未定义的偏移量:第31行上的/var/www/html/test/test.php中为0

第31行是我试图呼应比赛的地方。

$str = <<<HEREDOC
Content-Type: text/plain
Server: testapp (4.2.1 (x86_64/linux))
Content-Length: 125
{"password":"123","email_address":"","name":"j.doe","username":"jd123"}
HEREDOC;
preg_match('/('{.*'})/', $str, $matches);
echo $matches[0];

这里的正则表达式只是匹配一行,该行以{开始,以}结束。然而,这是一个快速而松散的正则表达式。

与其使用大模式来匹配所有内容(这很耗时),为什么不使用preg_split在您想要的位置将字符串切成两块呢?

$string = 'Content-Type: text/plain
   Server: testapp (4.2.1 (x86_64/linux))
   Content-Length: 125
   {"password":"123","email_address":"","name":"j.doe","username":"jd123"}'; 
$parts = preg_split ("/Content-Length:'s*'d+'s*/", $string);
echo "The string i want is '" . $parts[1] . "'";

输出:

The string i want is '{"password":"123","email_address":"","name":"j.doe","username":"jd123"}'

您可以完全避免使用regex,因为HTTP标头总是与响应体通过两个连续的换行符分隔开。

list($headers, $body) = explode("'n'n", $string);

或者对于windows风格的中断(顺便说一下,这是HTTP标头的标准):

list($headers, $body) = explode("'r'n'r'n", $string);