2013-09-25 103 views
0

我一直在不停地詢問並儘可能多地研究它,但我仍然找不到解決方案。在另一個字符串中查找自定義變量字符串

我有一個PHP應用程序,將有一些特定的標記,將啓動其他應用程序。

例如我將有這樣

%APP:name_of_the_app|ID:123123123% 

我需要搜索這種類型的標籤的字符串然後提取「APP」和「ID」的值的變量,我也有其他的令牌預定義,它們以%開始和結束,因此如果我必須使用不同的字符來打開和關閉可以使用的標記。

APP可以是字母數字,並可能包含 - 或_ ID只有數字

謝謝!

回答

3

與捕獲組A的正則表達式應該爲你工作(/%APP:(.*?)\|ID:([0-9]+)%/):

$string = "This is my string but it also has %APP:name_of_the_app|ID:123123123% a bunch of other stuff in it"; 

$apps = array(); 
if (preg_match_all("/%APP:(.*?)\|ID:([0-9]+)%/", $string, $matches)) { 
    for ($i = 0; $i < count($matches[0]); $i++) { 
     $apps[] = array(
      "name" => $matches[1][$i], 
      "id" => $matches[2][$i] 
     ); 
    } 
} 
print_r($apps); 

其中給出:

Array 
(
    [0] => Array 
     (
      [name] => name_of_the_app 
      [id] => 123123123 
     ) 

) 

或者,你可以使用strpossubstr做同樣的事情,但沒有具體說明令牌被調用(如果您在字符串的中間使用百分比符號,會出現錯誤):

<?php 
    $string = "This is my string but it also has %APP:name_of_the_app|ID:123123123|whatevertoken:whatevervalue% a bunch of other stuff in it"; 

    $inTag = false; 
    $lastOffset = 0; 

    $tags = array(); 
    while ($position = strpos($string, "%", $offset)) { 
     $offset = $position + 1; 
     if ($inTag) { 
      $tag = substr($string, $lastOffset, $position - $lastOffset); 
      $tagsSingle = array(); 
      $tagExplode = explode("|", $tag); 
      foreach ($tagExplode as $tagVariable) { 
       $colonPosition = strpos($tagVariable, ":"); 
       $tagsSingle[substr($tagVariable, 0, $colonPosition)] = substr($tagVariable, $colonPosition + 1); 
      } 
      $tags[] = $tagsSingle; 
     } 
     $inTag = !$inTag; 
     $lastOffset = $offset; 
    } 

    print_r($tags); 
?> 

其中給出:

Array 
(
    [0] => Array 
     (
      [APP] => name_of_the_app 
      [ID] => 123123123 
      [whatevertoken] => whatevervalue 
     ) 

) 

DEMO

+0

這是完美的!非常感謝!!! –

相關問題