2015-02-10 32 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);