PHP/REGEX:在括号内获取一个字符串 [英] PHP/REGEX: Get a string within parentheses
问题描述
这是一个非常简单的问题,但是我在任何地方都找不到解决方案.
This is a really simple problem, but I couldn't find a solution anywhere.
我尝试使用preg_match或preg_match_all从括号内获取字符串,但不带括号.
I'm try to use preg_match or preg_match_all to obtain a string from within parentheses, but without the parentheses.
到目前为止,我的表情看起来像这样:
So far, my expression looks like this:
\([A-Za-z0-9 ]+\)
并返回以下结果:
3(空心高光)928-129(<-原始字符串)
3(hollow highlight) 928-129 (<- original string)
(空心突出显示)(<-结果)
(hollow highlight) (<- result)
我想要的是括号内的字符串,但没有括号.看起来像这样:
What i want is the string within parentheses, but without the parentheses. It would look like this:
空心高亮
之后我可能会用str_replace之类的东西来代替括号,但这对我来说似乎不是一个很优雅的解决方案.
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.
我必须添加什么,因此结果中不包括括号?
What do I have to add, so the parentheses aren't included in the result?
感谢您的帮助,你们很棒! :)
Thanks for your help, you guys are great! :)
推荐答案
除了转义的括号外,您还需要添加捕获括号.
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]);
?>
这将输出:
Array ( [0] => world [1] => is andrew [2] => 845 )
这篇关于PHP/REGEX:在括号内获取一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!