PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to replace any brackets for rounded brackets using Regular Expression?

 November 20, 2022     php, preg-replace, regex, string     No comments   

Issue

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.


Solution

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

https://3v4l.org/URvcb



Answered By - user3783243
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing