0

How can I get only the text inside "()" For example from "(en) English" I want only the "en". I've written this pattern "/\(.[a-z]+\)/i" but it also gets the "()";

Thanks in advance.

5 Answers 5

2
<?php

$string = '(en) English';

preg_match('#\((.*?)\)#is', $string, $matches);

echo $matches[1]; # en

?>

$matches[0] will contain entire matches string, $matches[1] will first group, in this case (.*?) between ( and ).

Sign up to request clarification or add additional context in comments.

Comments

1

What is the dot in your regex good for, I assume its there by mistake.

Second to give you an alternative to the capturing group answer (which is perfectly fine!), here is to soltution using lookbehind and lookahead.

(?<=\()[a-z]+(?=\))

See it here on Regexr

The trick here is, those lookarounds do not match the characters inside, they just check if they are there. So those characters are not included in the result.

(?<=\() positive look behind assertion, checking for the character ( before its position

(?=\) positive look ahead assertion, checking for the character ( ahead of its position

Comments

0

That should do the job.

"/\(([a-z]+)\)/i"

Comments

0

The easiest way is to get "/\(([a-z]+)\)/i" and use the capture group to get what you want.

Otherwise, you have to get into look ahead, look behinds

Comments

0

You could use a capture group like everyone else proposes

OR

you can make your match only check if your match is preceded by "(" and followed by ")". It's called Lookahead and lookbehind.

"/(?<=\().[a-z]+(?=\))/i"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.