PHP/REGEX:获取括号内的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11249445/
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/REGEX: Get a string within parentheses
提问by Macks
This is a really simple problem, but I couldn't find a solution anywhere.
这是一个非常简单的问题,但我在任何地方都找不到解决方案。
I'm try to use preg_match or preg_match_all to obtain a string from within parentheses, but without the parentheses.
我尝试使用 preg_match 或 preg_match_all 从括号内获取字符串,但没有括号。
So far, my expression looks like this:
到目前为止,我的表情是这样的:
\([A-Za-z0-9 ]+\)
and returns the following result:
并返回以下结果:
3(hollow highlight) 928-129 (<- original string)
(hollow highlight) (<- result)
3(空心高亮)928-129(<-原始字符串)
(空心突出显示)(<- 结果)
What i want is the string within parentheses, but without the parentheses. It would look like this:
我想要的是括号内的字符串,但没有括号。它看起来像这样:
hollow highlight
空心亮点
I could probably replace the parentheses afterwards with str_replace or something, but that doesn't seem to be a very elegant solution to me.
之后我可能可以用 str_replace 或其他东西替换括号,但这对我来说似乎不是一个非常优雅的解决方案。
What do I have to add, so the parentheses aren't included in the result?
我必须添加什么,以便括号不包含在结果中?
Thanks for your help, you guys are great! :)
谢谢你的帮助,你们很棒!:)
回答by Piotr Olaszewski
try:
尝试:
preg_match('/\((.*?)\)/', $s, $a);
output:
输出:
Array
(
[0] => (hollow highlight)
[1] => hollow highlight
)
回答by Andrew Cheong
You just need to add capturing parenthesis, in addition to your escaped parenthesis.
除了转义括号之外,您只需要添加捕获括号。
<?php
$in = "hello (world), my name (is andrew) and my number is (845) 235-0184";
preg_match_all('/\(([A-Za-z0-9 ]+?)\)/', $in, $out);
print_r($out[1]);
?>
This outputs:
这输出:
Array ( [0] => world [1] => is andrew [2] => 845 )

