如何使用条件前缀[+
和后缀+]
获取部分字符串,然后在数组中返回所有字符串?
示例:
$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;
}
非常感谢...
答案 0 :(得分: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();
}
答案 1 :(得分:2)
以下是strtok
的解决方案:
function getStack ($string, $prefix='[+', $suffix='+]') {
$matches = array();
strtok($string, $prefix);
while (($token = strtok($suffix)) !== false) {
$matches[] = $token;
strtok($prefix);
}
return $matches;
}