2010-11-14 69 views
4

如何獲得條件前綴[+和後綴+]的字符串部分,然後將其全部返回到數組中?如果使用條件前綴[+和後綴+]獲取字符串的一部分

例如:

$string = 'Lorem [+text+] Color Amet, [+me+] The magic who [+do+] this template'; 

// function to get require 
function getStack ($string, $prefix='[+', $suffix='+]') { 
    // how to get get result like this? 
    $result = array('text', 'me', 'do'); // get all the string inside [+ +] 

    return $result; 
} 

許多感謝...

+1

這應該是一個相當簡單的正則表達式。像'preg_match_all(「/\\[\\+(.*?)\\+\\]/」);'然後得到結果的組1。 – Alxandr 2010-11-14 05:20:06

回答

5

您可以使用preg_match_all爲:

function getStack ($string, $prefix='[+', $suffix='+]') { 
     $prefix = preg_quote($prefix); 
     $suffix = preg_quote($suffix); 
     if(preg_match_all("!$prefix(.*?)$suffix!",$string,$matches)) { 
       return $matches[1]; 
     } 
     return array(); 
} 

Code In Action

+0

答案是正確的地方...非常感謝你:D – GusDeCooL 2010-11-14 05:41:59

+1

你可能想添加分隔符'/'到'preg_quote()'調用。 – BoltClock 2010-11-14 16:13:47

+1

@codaddict:我想你誤解了BoltClock。 'preg_quote'不會脫離分隔符,除非它是PCRE的特殊字符之一。因此,如果您使用'/'或'!'作爲分隔符,則需要將它傳遞給'preg_quote'以使其轉義。 – Gumbo 2010-11-14 16:43:43

2

下面是與strtok一個解決方案:

function getStack ($string, $prefix='[+', $suffix='+]') { 
    $matches = array(); 
    strtok($string, $prefix); 
    while (($token = strtok($suffix)) !== false) { 
     $matches[] = $token; 
     strtok($prefix); 
    } 
    return $matches; 
} 
+0

WOW ...謝謝你。我第一次看到函數'strtok':D – GusDeCooL 2010-11-16 03:14:42