PHP如何用空格替换字符串?

时间:2018-12-15 11:09:47

标签: php str-replace

输入:

  

古杰拉特(24)

预期输出:

  

24

字符串格式:

  

州名(州代码)

如何删除带有括号的州代码?

5 个答案:

答案 0 :(得分:0)

您也可以使用php explode

$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT

答案 1 :(得分:0)

您可以使用功能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 :(得分:0)

如果您知道stateCode的长度,并且它是固定的

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

您可以在php手册中查看有关substrstrpos的更多信息。

如果stateCode的长度不固定,则可以使用正则表达式:-

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

答案 3 :(得分:0)

string id = txt.Substring(0, txt.LastIndexOf("UID:") + 9);

答案 4 :(得分:0)

let str = "LOREM Ipsum is simply DUMMY text of the printing and typesetting industry. Lorem IPSUM. Has been the industry's standard dummy text ever since the 1500s, WHEN an unknown printer took a galley."

let op = str.toLowerCase().replace(/^([a-z])|\.\s*([a-z])/g, (match)=>match.toUpperCase())
console.log(op)