开发者

Howto preg_replace a specific char within parentheses?

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 :)


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);


You have to capture the characters next to the ;:

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜