PHP:返回两个字符之间的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2047337/
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
PHP: Return string between two characters
提问by Nic Hubbard
I am wanting to use "keywords" within a large string. These keywords start and end using my_keywordand are user defined. How, within a large string, can I search and find what is between the two * characters and return each instance?
我想在一个大字符串中使用“关键字”。这些关键字以my_keyword开始和结束,并且是用户定义的。如何在大字符串中搜索并找到两个 * 字符之间的内容并返回每个实例?
The reason it might change it, that parts of the keywords can be user defined, such as page_date_Ywhich might show the year in which the page was created.
它可能会改变它的原因,部分关键字可以是用户定义的,例如page_date_Y可能显示页面创建的年份。
So, again, I just need to do a search and return what is between those * characters. Is this possible, or is there a better way of doing this if I don't know the "keyword" length or what i might be?
所以,同样,我只需要进行搜索并返回这些 * 字符之间的内容。这是可能的,或者如果我不知道“关键字”长度或我可能是什么,有没有更好的方法来做到这一点?
回答by codaddict
<?php
// keywords are between *
$str = "PHP is the *best*, its the *most popular* and *I* love it.";
if(preg_match_all('/\*(.*?)\*/',$str,$match)) {
var_dump($match[1]);
}
?>
Output:
输出:
array(3) {
[0]=>
string(4) "best"
[1]=>
string(12) "most popular"
[2]=>
string(1) "I"
}
回答by ghostdog74
Explode on "*"
在“*”上爆炸
$str = "PHP is the *best*, *its* the *most popular* and *I* love it.";
$s = explode("*",$str);
for($i=1;$i<=count($s)-1;$i+=2){
print $s[$i]."\n";
}
output
输出
$ php test.php
best
its
most popular
I
回答by jtrick
If you want to extract a string that's enclosed by two differentstrings (Like something in parentheses, brackets, html tags, etc.), here's a post more specific to that:
如果要提取由两个不同字符串(例如括号、方括号、html 标签等中的内容)括起来的字符串,这里有一篇更具体的文章:
回答by Alix Axel
Here ya go:
给你:
function stringBetween($string, $keyword)
{
$matches = array();
$keyword = preg_quote($keyword, '~');
if (preg_match_all('~' . $keyword . '(.*?)' . $keyword . '~s', $string, $matches) > 0)
{
return $matches[1];
}
else
{
return 'No matches found!';
}
}
Use the function like this:
像这样使用函数:
stringBetween('1 *a* 2 3 *a* *a* 5 *a*', '*a*');

