2

Input:

GUJARAT (24)

Output:

GUJARAT

String Format

State Name (State Code)

I want to remove state code with parentheses. How can I do this by using regex in PHP?

2
  • 2
    Have you made any effort to solve this problem yourself? Stack Overflow is not a free code writing service. Welcome to the site, by the way. Commented Dec 7, 2018 at 5:52
  • Can you have several states on same string? Like in FOO (123) ... BAR (456) Commented Dec 7, 2018 at 10:18

4 Answers 4

2

You can try this

(?<=\s)(\(.*\))

Explanation

  • (?<=\s) - Positive look behind. Matches \s (a white space).
  • (\(.*\)) - Matches ( some random text)

Demo

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

2 Comments

It could fail if there are several states on the same string, like in GUJARAT (24) OTHER (14). Not specified by requirements, though. Anways an ungreedy star could be a nice addition
@Julio Yeah but he specified string format in question. so i wrote according to that. Btw thanks for suggestion :)
1

Using RegEx

$text="GUJARAT (24)"
$statename=preg_replace("/\([^)]+\)/","",$text);

Comments

0

In case you don't want to use regex you can also use simple strpos and substr.
This is a lighter way to do it than using regex (less meory useage).
The code finds the ( and removes everything one step behind and forward.

$arr = ["GUJARAT (24)", "State Name (State Code)"];

foreach($arr as $val){
    echo substr($val, 0, strpos($val, "(")-1) . "\n";    
}
// GUJARAT
// State Name

https://3v4l.org/IdvAI

Comments

0

Try this one too.

 $text="GUJARAT (24)";
 $statename= preg_replace("/[(][0-9]*[)]/","",$text);
 echo $statename;

1 Comment

That {1} seems to be unneded

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.