2015-02-10 89 views
0

我在一个字符串名为$测试下面的文字出现故障:正则表达式,没有错误

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]; 
?> 

这给了我以下错误:

Undefined offset: 0 in /var/www/html/test/test.php on line 31

第31行就是我试图呼应比赛。

+0

它与任何内容不匹配 – Cfreak 2015-02-10 21:58:28

+0

而且您应该看到其他错误,因为您正在脱离字符串。再次尝试我的答案... – 2015-02-10 21:59:24

+0

你在文字后有无与伦比的空白。在正则表达式中的第一个之后添加空格。 – 2015-02-10 22:59:35

回答

0
$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]; 

这里的正则表达式被简单地匹配与{开始和结束}的线。然而,这是一个快速而宽松的正则表达式。

+0

似乎没有工作...请参阅我的编辑1.谢谢! – Happydevdays 2015-02-10 21:55:08

+1

你应该解释这是什么。由于很多原因,它不是一个很好的正则表达式。 – Cfreak 2015-02-10 21:59:11

+0

你需要至少躲过大括号。 – chris85 2015-02-10 22:04:49

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"}' 
0

可避免完全正则表达式,因为HTTP标头,则响应主体由2个consecutives换行符总是分离。

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

对于Windows风格的中断(其中的方式是HTTP头的标准):在你的编辑你检查`$ str`,而不是`$ test`

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