gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:26:24 24 4
gpt4 key购买 nike

我有这个输入:

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

你能帮我看看这个函数的问题在哪里吗?看起来那工作与我需要的相反,不是吗?
谢谢你。

最佳答案

$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 «\]»

演示: http://ideone.com/wVvssx

关于php - 在两个字符串之间的字符串中获取多个匹配项 - 我使用的函数中的小问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com