duandun2218 2015-04-18 21:05
浏览 25
已采纳

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

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 2015-04-18 21:11
    关注
    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!