duandun2218
duandun2218
2015-04-18 21:05

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

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanhuang7591 duanhuang7591 6年前
    $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

    点赞 评论 复制链接分享