如何 preg_replace 括号内的特定字符?

发布于 2024-10-20 21:05:30 字数 304 浏览 3 评论 0原文

我得到了一堆像这样的字符串:

test; test2 (2;5%).

我现在想要用 PHP 做的是纠正“;”在括号中,所以它看起来像:

test; test2 (2,5%) - mention the ",".

我尝试过的代码:

$string = preg_replace("/\(.;.\)/", ",", $string);

我的眼睛实际上因谷歌搜索而流血,所以请帮我解决这个问题:)

I got a bunch of strings like this one:

test; test2 (2;5%).

What I want to do with PHP now is to correct the ";" in the parentheses so it will look like:

test; test2 (2,5%) - mention the ",".

Code that I tried:

$string = preg_replace("/\(.;.\)/", ",", $string);

My eyes actually bleed from googling so please help me out with that :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫七 2024-10-27 21:05:30

1) 需要用反斜杠 (\) 转义括号

2) 表达式中没有包含百分号

3) 本来可以用单个 < 替换整个括号表达式(包括括号) code>,

4) 正如 Zimzat 在评论中指出的那样,用 \d+ 替换句点 (.) 可能是一个更好的主意,它匹配数字而不是任何字符。

$string = preg_replace("/\((\d+);(\d+%)\)/", "($1,$2)", $string);

1) Needed to escape the parenthesis with a backslash (\)

2) Didn't include the percent sign in your expression

3) Would have been replacing the entire bracketed expression (brackets included) with a single ,

4) As Zimzat points out in the comments, it might be a better idea to replace the periods (.) with \d+, which matches numbers instead of any character.

$string = preg_replace("/\((\d+);(\d+%)\)/", "($1,$2)", $string);
落叶缤纷 2024-10-27 21:05:30

您必须捕获 ; 旁边的字符:

$string = preg_replace('/\((\d+);(\d+%)\)/', "($1,$2)", $string);

You have to capture the characters next to the ;:

$string = preg_replace('/\((\d+);(\d+%)\)/', "($1,$2)", $string);
相权↑美人 2024-10-27 21:05:30

要替换 () 中多次出现的例如逗号,我将使用此代码

  $text = preg_replace_callback("/\{((.*),(.*))\}/sim", function($matches){
    return str_replace(',', ':comma:', $matches[0]);
  }, $text);

to replace multiple occurences of eg comma in () i will use this code

  $text = preg_replace_callback("/\{((.*),(.*))\}/sim", function($matches){
    return str_replace(',', ':comma:', $matches[0]);
  }, $text);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文