2010-11-14 58 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