How can I get part of the string with conditional prefix [+
and suffix +]
, and then return all of it in an array?
example:
$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;
}
many thanks...
A prefix of a string S is a substring of S that occurs at the beginning of S. A suffix of a string S is a substring that occurs at the end of S.
The match_results::prefix() is an inbuilt function in C++ which is used to get the string which is preceding the matched string in the input target string.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc".
You can use preg_match_all as:
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
Here’s a solution with strtok
:
function getStack ($string, $prefix='[+', $suffix='+]') {
$matches = array();
strtok($string, $prefix);
while (($token = strtok($suffix)) !== false) {
$matches[] = $token;
strtok($prefix);
}
return $matches;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With