2017-07-03 65 views
0

我正在使用正則表達式來檢查某種格式的字符串。PHP提取(解析)字符串

preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE); 

使用該正則表達式,所張貼的串需要具有以下格式:

/答案NX

N - >> 0的整數

X - >一字符串,最多512個字符

現在如何提取「n」和「x」是最簡單的方法g PHP? 例如:

/回答56這是我的示例文本

應導致:

$value1 = 56; 
$value2 = "this is my sample text"; 
+0

'$ hit'中有什麼? –

+0

$ hit是空的。不必要。 – seikzer

+1

'$ hit'存儲匹配項。你在'preg_match'後面打印了嗎? –

回答

1

運行這個簡單的代碼

<?php 
$hit = []; 
$str = '/answer 56 this is my sample text'; 
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE); 
echo'<pre>',print_r($hit),'</pre>'; 

將顯示你,那$hit有以下值:

<pre>Array 
(
    [0] => Array 
     (
      [0] => /answer 56 this is my sample text 
      [1] => 0 
     ) 

    [1] => Array 
     (
      [0] => 56 
      [1] => 8 
     ) 

    [2] => Array 
     (
      [0] => this is my sample text 
      [1] => 11 
     ) 

) 
1</pre> 

這裏:

  • $hit[0][0]是您的模式
  • $hit[1][0]匹配完全字符串匹配模式[1-9][0-9]*
  • $hit[2][0]是匹配模式.{1,512}
一個子一個子

所以,

$value1 = $hit[1][0]; 
$value2 = $hit[2][0];