Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/REGEX: Get a string within parentheses

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.

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)

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.

What do I have to add, so the parentheses aren't included in the result?

Thanks for your help, you guys are great! :)

like image 959
Macks Avatar asked Jun 28 '12 16:06

Macks


People also ask

How do you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.


2 Answers

try:

preg_match('/\((.*?)\)/', $s, $a);

output:

Array
(
    [0] => (hollow highlight)
    [1] => hollow highlight
)
like image 53
Piotr Olaszewski Avatar answered Oct 14 '22 14:10

Piotr Olaszewski


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 ) 
like image 16
slackwing Avatar answered Oct 14 '22 12:10

slackwing