php 提取花括号regex php之间的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20838624/
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
Extracting all values between curly braces regex php
提问by Ganesh Babu
I have content in this form
我有这种形式的内容
$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
I need all the values between curly braces in an array like the one shown below:
我需要一个数组中大括号之间的所有值,如下所示:
array("0"=>"123456","1"=>"7894560","2"=>"145789")
I tried with this code:
我尝试使用此代码:
<?php
preg_match_all("/\{.*}\/s", $content, $matches);
?>
But I am getting in here values from first curly brace to the last found in the content. What can be done to get the array in above format? I knew that the pattern I have used is wrong. What shall be given to get desired output shown above?
但是我在这里输入了从第一个大括号到内容中最后一个大括号的值。可以做些什么来获得上述格式的数组?我知道我使用的模式是错误的。要获得上面显示的所需输出,应给予什么?
回答by Shankar Damodaran
Do like this...
这样做...
<?php
$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
preg_match_all('/{(.*?)}/', $content, $matches);
print_r(array_map('intval',$matches[1]));
OUTPUT :
输出 :
Array
(
[0] => 123456
[1] => 7894560
[2] => 145789
)
回答by zx81
Two compact solutions weren't mentioned:
没有提到两个紧凑的解决方案:
(?<={)[^}]*(?=})
and
和
{\K[^}]*(?=})
These allow you to access the matches directly, without capture groups. For instance:
这些允许您直接访问匹配项,而无需捕获组。例如:
$regex = '/{\K[^}]*(?=})/m';
preg_match_all($regex, $yourstring, $matches);
// See all matches
print_r($matches[0]);
Explanation
解释
- The
(?<={)lookbehind asserts that what precedes is an opening brace. - In option 2,
{matches the opening brace, then\Ktells the engine to abandon what was matched so far.\Kis available in Perl, PHP and R (which use thePCREengine), and Ruby 2.0+ - The
[^}]negated character class represents one character that is not a closing brace, - and the
*quantifier matches that zero or more times - The lookahead
(?=})asserts that what follows is a closing brace.
- 在
(?<={)回顾后发断言,什么是先于一开口梅开二度。 - 在选项 2 中,
{匹配左括号,然后\K告诉引擎放弃目前匹配的内容。\K在 Perl、PHP 和 R(使用PCRE引擎)和 Ruby 2.0+ 中可用 - 在
[^}]否定字符类代表一个字符不是一个右括号, - 并且
*量词匹配零次或多次 - 前瞻
(?=})断言接下来是一个右大括号。
Reference
参考
回答by Awlad Liton
DEMO :https://eval.in/84197
演示:https: //eval.in/84197
$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
preg_match_all('/{(.*?)}/', $content, $matches);
foreach ($matches[1] as $a ){
echo $a." ";
}
Output:
输出:
123456 7894560 145789

