0

Input:

GUJARAT (24)

Expected Output:

24

String Format:

State Name (State Code)

How can I remove State Code with parentheses?

1
  • This question is very ambiguous in its expectations -- making it Unclear. Commented Feb 25, 2022 at 1:20

5 Answers 5

0

You can also use php explode:

$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT
Sign up to request clarification or add additional context in comments.

1 Comment

Oh Sorry, my expected output is state code, not a state name. Please help me.
0
$str = "GUJARAT (24)";
echo '<br />1.';
print_r(sscanf($str, "%s (%d)"));
echo '<br />2.';
print_r(preg_split('/[\(]+/', rtrim($str, ')')));
echo '<br />3.';
echo substr($str, strpos($str, '(')+1, strpos($str, ')')-strpos($str, '(')-1);
echo '<br />4.';
echo strrev(strstr(strrev(strstr($str, ')', true)), '(', true));
echo '<br />5.';
echo preg_replace('/(\w+)\s+\((\d+)\)/', "$2", $str);

Comments

0

If you know the stateCode length, and it is fixed

$state = "GUJARAT (24)";
$state = substr($state, strpos($state, "(") + 1, 2);
// get string upto "(", and remove right white space    
echo $state;

You can check more about substr and strpos in php manual.

If stateCode length is not fixed, you can use regular expression:-

  $state = 'GUJARAT (124)';
  preg_match('/(\d+)/', $state, $res);
  $stateCode = $res[0]; 
  var_dump($stateCode);

1 Comment

Oh Sorry, my expected output is state code, not a state name. Please help me.
0
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');

echo $parsed; // (result = dog)

Comments

-1

you can use the function preg_match

$state = 'GUJARAT (24)'
$result = [];
preg_match('/[\(][\d]+[\)]/', $state, $result);
$stateCode = $result[0] // (24)
$stateCode = substr($stateCode, 1, strlen($stateCode) - 2); // will output 24

2 Comments

Oh Sorry, my expected output is state code, not a state name. Please help me.
I do not recommend that anyone copy this regex. Even if the OP wanted the state id as the result, there is much to correct in the pattern. You shouldn't ever need to call substr() or strlen() if you use a capture group.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.