Reputation: 37
Here is code:
$string="{1},[2],(3),<4>";
// Replaces closing square, curly, angle brackets with round brackets
$string = preg_replace('/\{\[\</', '(', $string);
$string = preg_replace('/\}\]\>/', ')', $string);
It didn't replace at all in that string... Any better coding than that?
Thanks.
Upvotes: 1
Views: 1631
Reputation: 627087
You may use
$string="{1},[2],(3),<4>";
$what = ['~[{[<]~', '~[]}>]~'];
$with = ['(', ')'];
$string = preg_replace($what, $with, $string);
echo $string;
Here,
[{[<]
- a character class that matches one of the three chars: {
, [
or <
[]}>]
- matches one of the three chars: ]
, }
or >
(note that ]
inside the character class does not have to be escaped when it is the first char in the class).See the PHP demo.
You may use a single call to preg_replace_callback
, too:
$string = preg_replace_callback('~([{[<])|[]}>]~', function ($m) {
return !empty($m[1]) ? "(" : ")";
}, $string);
See this PHP demo.
The ([{[<])
pattern captures the opening punctuation into Group 1 ($m[1]
) and if the group is not empty after a match is found, (
is returned, else, )
is replaced with.
Upvotes: 2
Reputation: 78994
No need for regex here:
$string = str_replace(['{','[','<'], '(', str_replace(['}',']','>'], ')', $string));
Or use one call to strtr
but the array will be longer.
Upvotes: 2
Reputation: 715
Unless you need regular expressions, avoid them. This can be done by simple string replacement, e.g.
<?php
$string = "{1},[2],(3),<4>";
$string = strtr($string, ['{' => '(', '}' => ')', '[' => '(', ']' => ')', '<' => '(', '>' => ')']);
Upvotes: 2
Reputation: 5224
{[<
never occurs in your string. Use a character class or optional grouping.
$string = preg_replace('/[{[<]/', '(', $string);
$string = preg_replace('/[}>\]]/', ')', $string);
Alternative non character class approach:
$string = preg_replace('/(?:\{|<|\[)/', '(', $string);
$string = preg_replace('/(?:\}|>|\])/', ')', $string);
Upvotes: 1