php PHP获取标签之间的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25817248/
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 get string between tags
提问by asdf23e32
I got a string like this which is (Joomla all video plugin)
我有一个这样的字符串(Joomla all video plugin)
{Vimeo}123456789{/Vimeo}
where 123456789 is variable, how can I extract this? Should I use regex?
其中 123456789 是可变的,我如何提取它?我应该使用正则表达式吗?
回答by hwnd
If you must use a regular expression, the following will do the trick.
如果您必须使用正则表达式,下面的方法可以解决问题。
$str = 'foo {Vimeo}123456789{/Vimeo} bar';
preg_match('~{Vimeo}([^{]*){/Vimeo}~i', $str, $match);
var_dump($match[1]); // string(9) "123456789"
This may be more than what you want to go through, but here is a way to avoid regex.
这可能比您想要经历的要多,但这里有一种避免正则表达式的方法。
$str = 'foo {Vimeo}123456789{/Vimeo} bar';
$m = substr($str, strpos($str, '{Vimeo}')+7);
$m = substr($m, 0, strpos($m, '{/Vimeo}'));
var_dump($m); // string(9) "123456789"
回答by Thank you
Here's another solution for you
这是您的另一个解决方案
$str = "{Vimeo}123456789{/Vimeo}";
preg_match("/\{(\w+)\}(.+?)\{\/\1\}/", $str, $matches);
printf("tag: %s, body: %s", $matches[1], $matches[2]);
Output
输出
tag: Vimeo, body: 123456789
Or you could build it into a function like this
或者你可以将它构建成这样的函数
function getTagValues($tag, $str) {
$re = sprintf("/\{(%s)\}(.+?)\{\/\1\}/", preg_quote($tag));
preg_match_all($re, $str, $matches);
return $matches[2];
}
$str = "{Vimeo}123456789{/Vimeo} and {Vimeo}123{/Vimeo}";
var_dump(getTagValues("Vimeo", $str));
Output
输出
array(2) {
[0]=>
string(9) "123456789"
[1]=>
string(3) "123"
}
回答by Rahul Tripathi
You may try like this:
你可以这样尝试:
$string = '{Vimeo}123456789{/Vimeo} ';
echo extractString($string, '{Vimeo}', '{/Vimeo}');
function extractString($string, $start, $end) {
$string = " ".$string;
$ini = strpos($string, $start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
回答by derdida
Yes, you could use regex.Like this:
是的,你可以使用正则表达式。像这样:
preg_match_all('/{Vimeo}(.*?){\/Vimeo}/s', $yourstring, $matches);
回答by FlyingNimbus
If the buildup is always like that you could also replace the tags by nothing
如果堆积总是这样,你也可以什么都不替换标签
$string = '{Vimeo}123456789{/Vimeo}';
str_replace(array('{Vimeo}', '{/Vimeo}'), '', $string);