[英]PHP How to Replace string with empty space?
Input: 输入:
GUJARAT (24)
古杰拉特(24)
Expected Output: 预期产量:
24
24
String Format: 字串格式:
State Name (State Code)
州名(州代码)
How can I remove State Code with parentheses? 如何删除带有括号的州代码?
You can also use php explode : 您还可以使用php explode :
$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT
you can use the function preg_match 您可以使用功能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
If you know the stateCode length, and it is fixed 如果您知道stateCode的长度,并且它是固定的
$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. 您可以在php手册中查看有关substr和strpos的更多信息。
If stateCode length is not fixed, you can use regular expression:- 如果stateCode的长度不固定,则可以使用正则表达式:
$state = 'GUJARAT (124)';
preg_match('/(\d+)/', $state, $res);
$stateCode = $res[0];
var_dump($stateCode);
$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);
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.