2012-06-08 180 views
4
$string1 = "This is test [example]"; 
$string2 = "This is test [example][2]"; 
$string3 = "This [is] test [example][3]"; 

如何獲得以下結果?如何獲得兩個字符[字符串]之間的字符串? PHP

For $string1 -> example 
For $string2 -> example*2 
For $string3 -> is*example*3 
+0

在任何語言中,遍歷字符,如果你遇到'['設置的標誌,並抓住一切直到']'和取消標誌:) – Jashwant

回答

7
preg_match_all('/\[([^\]]+)\]/', $str, $matches); 

php > preg_match_all('/\[([^\]]+)\]/', 'This [is] test [example][3]', $matches); 
php > print_r($matches); 
Array 
(
    [0] => Array 
     (
      [0] => [is] 
      [1] => [example] 
      [2] => [3] 
     ) 

    [1] => Array 
     (
      [0] => is 
      [1] => example 
      [2] => 3 
     ) 

) 

而這裏的rregex的解釋:

\[ # literal [ 
(# group start 
    [^\]]+ # one or more non-] characters 
) # group end 
\] # literal ] 
+0

你能解釋一下請正則表達式? 據我所知。 '/'開始正則表達式。 '\'來轉義'['。 ''包括一組字符?對 ?你能解釋完整的正則表達式嗎? – Jashwant

5

對於那些警惕正則表達式,這裏有一個解決方案SANS那個瘋狂的正則表達式語法。 :-)它曾經真的激怒了我這樣的事情是不是原產於PHP的字符串函數,所以我建一個...

// Grabs the text between two identifying substrings in a string. If $Echo, it will output verbose feedback. 
function BetweenString($InputString, $StartStr, $EndStr=0, $StartLoc=0, $Echo=0) { 
    if (!is_string($InputString)) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. \$InputString is not a string.</p>\n"; } return; } 
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. Could not find \$StartStr '{$StartStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).</p>\n"; } return; } 
    $StartLoc += strlen($StartStr); 
    if (!$EndStr) { $EndStr = $StartStr; } 
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { if ($Echo) { echo "<p>html_tools.php BetweenString() FAILED. Could not find \$EndStr '{$EndStr}' within \$InputString |{$InputString}| starting from \$StartLoc ({$StartLoc}).</p>\n"; } return; } 
    $BetweenString = substr($InputString, $StartLoc, ($EndLoc-$StartLoc)); 
    if ($Echo) { echo "<p>html_tools.php BetweenString() Returning |'{$BetweenString}'| as found between \$StartLoc ({$StartLoc}) and \$EndLoc ({$EndLoc}).</p>\n"; } 
    return $BetweenString; 
} 

當然,這可以濃縮了不少。爲了節省別人清除它的努力:

// Grabs the text between two identifying substrings in a string. 
function BetweenStr($InputString, $StartStr, $EndStr=0, $StartLoc=0) { 
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { return; } 
    $StartLoc += strlen($StartStr); 
    if (!$EndStr) { $EndStr = $StartStr; } 
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { return; } 
    return substr($InputString, $StartLoc, ($EndLoc-$StartLoc)); 
} 
相關問題