I have this input:
somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters
And I need to get this output:
array("object1", "object2", "object3");
I use this function:
function get_string_between($string, $start, $end){
$split_string = explode($end,$string);
foreach($split_string as $data) {
$str_pos = strpos($data,$start);
$last_pos = strlen($data);
$capture_len = $last_pos - $str_pos;
$return[] = substr($data,$str_pos+1,$capture_len);
}
return $return;
}
So:
$input = "somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters";
$start = "[code]";
$end = "[/code]";
$outputs = get_string_between($input, $start, $end);
foreach($outputs as $output)
echo "$output </br>";
But foreach return this:
code]object1
code]object2
code]object3
omerandomcharacters
Can you please help me where is the problem in the function? It looks like that work opposite than I need, isn't it? Thank you.
$string = "somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters";
preg_match_all('%\[code\](.*?)\[/code\]%i', $string, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);
Output:
Array
(
[0] => object1
[1] => object2
[2] => object3
)
Regex Explanation:
\[code\](.*?)\[/code\]
Options: Case insensitive
Match the character “[” literally «\[»
Match the character string “code” literally (case insensitive) «code»
Match the character “]” literally «\]»
Match the regex below and capture its match into backreference number 1 «(.*?)»
Match any single character that is NOT a line break character (line feed) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “[” literally «\[»
Match the character string “/code” literally (case insensitive) «/code»
Match the character “]” literally «\]»
DEMO: http://ideone.com/wVvssx