在两个字符串之间的字符串中获取多个匹配项 - 我使用的函数中的小问题?

时间:2015-04-18 21:05:07

标签: php

我有这个输入:

somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters

我需要得到这个输出:

array("object1", "object2", "object3");

我使用这个功能:

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;
}

所以:

    $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>";

但是foreach返回了这个:

code]object1 
code]object2 
code]object3 
omerandomcharacters 

你能帮我解决一下这个功能的问题吗?看起来这项工作与我需要的相反,不是吗? 谢谢。

1 个答案:

答案 0 :(得分:3)

$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]);

<强>输出:

Array
(
    [0] => object1
    [1] => object2
    [2] => object3
)

正则表达式说明:

\[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