php 使用php从以开头和结尾的字符串中获取所有匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14308154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:03:28  来源:igfitidea点击:

Get all matches from string that start with and end, using php

phpregexpreg-matchpreg-match-all

提问by Jeroen

How would I use PHP to extract everything in between [startstring]and [endstring]from this string:

我怎么会在两者之间使用PHP提取物的一切[startstring],并[endstring]从该字符串:

[startstring]hello = guys[endstring] hello guys [startstring]jerk = you[endstring] welcome to the universe

I'd like to find all the matches of [startstring]and [endstring], and echo the text inside. Kinda like a delimiter. And I would like all the matches echoed to be seperated by a space.

我想找到[startstring]and 的所有匹配项[endstring],并回显里面的文本。有点像分隔符。我希望所有回声的匹配项都由一个空格分隔。

How would I go about accomplishing this? Would this require regex? Could you provide a sample?

我将如何实现这一目标?这需要regex吗?你能提供一个样品吗?

Thanks so much! :)

非常感谢!:)

回答by Jeroen

preg_match_all('/\[startstring\](.*?)\[endstring\]/s', $input, $matches);
echo implode(' ', $matches);


preg_match_all('/\[startstring\](.*?)\=(.*?)\[endstring\]/s', $input, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
    $key = $matches[1][$i];
    $value = $matches[2][$i];
    $$key = $value;
}

回答by hsz

Try with preg_match_all:

尝试preg_match_all

preg_match_all('/\[startstring\](.*?)\[endstring\]/', $input, $matches);
var_dump($matches);