php 如何从php中的字符串中删除括号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8972063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:53:55  来源:igfitidea点击:

How to remove brackets from string in php?

phpstringpreg-replacestr-replace

提问by hairynuggets

I have the following string and would like to use str_replace or preg_replace to remove the brackets but am unsure how. I have been able to remove the opening brackets using str_replace but can't remove the closing brackets.

我有以下字符串,想使用 str_replace 或 preg_replace 删除括号,但我不确定如何。我已经能够使用 str_replace 删除左括号,但无法删除右括号。

This is the sting:

这是刺痛:

$coords = '(51.50972493425563, -0.1323877295303646)';

I have tried:

我试过了:

<?php echo str_replace('(','',$coords); ?>

which removed the opening brackets but am now under the impression that I need preg_replace to remove both.

它删除了左括号,但现在的印象是我需要 preg_replace 来删除两者。

How does one go about this?

如何解决这个问题?

Help appreciated

帮助表示赞赏

回答by hsz

Try with:

尝试:

str_replace(array( '(', ')' ), '', $coords);

回答by Sarfraz

If brackets always come on beginging and end, you can use trimeasily:

如果括号总是出现在开头和结尾,您可以trim轻松使用:

$coords = trim($coords, '()');

Result:

结果:

51.50972493425563, -0.1323877295303646

回答by symcbean

echo str_replace(
     array('(',')'), array('',''), 
     $coords);

or just do str_replace twice....

或者只是做 str_replace 两次....

echo str_replace(')', '', str_replace('(','',$coords));

回答by rauschen

it is easier than you think, str_replace can have an array as first parameter

这比你想象的要容易,str_replace 可以有一个数组作为第一个参数

 <?php echo str_replace(array('(',')'),'',$coords); ?>

回答by Stefan Koenen

i think you need to write your coords here as a string else you get syntax error ;). Anyway, this is the solution i think.

我认为你需要在这里写你的坐标作为一个字符串,否则你会得到语法错误;)。无论如何,这是我认为的解决方案。

$coords = "(51.50972493425563, -0.1323877295303646)";

$aReplace = array('(', ')');
$coordsReplaced = str_replace($aReplace , '', $coords);

Greets, Stefan

问候,斯蒂芬