如果使用条件前缀[+和后缀+],则获取字符串的一部分

Gus*_*ooL 5 php string

如何使用条件前缀[+和后缀获取字符串的一部分+],然后在数组中返回所有字符串?

例:

$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;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢...

cod*_*ict 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();
}
Run Code Online (Sandbox Code Playgroud)

代码在行动