0

Input:

GUJARAT (24)

Expected Output:

24

String Format:

State Name (State Code)

How can I remove State Code with parentheses?

Panda
  • 6,955
  • 6
  • 40
  • 55

5 Answers5

0

You can also use php explode:

$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT
Naveed
  • 41,517
  • 32
  • 98
  • 131
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);
Gautam Rai
  • 2,445
  • 2
  • 21
  • 31
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);
Sven Liivak
  • 1,323
  • 9
  • 10
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)
-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
Wonkledge
  • 1,732
  • 7
  • 16
  • 1
    Oh Sorry, my expected output is state code, not a state name. Please help me. – Rushabh Shah Dec 15 '18 at 12:14
  • 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. – mickmackusa Feb 25 '22 at 01:17