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

Sunday, November 20, 2022

[FIXED] How to replace everything between {} [] () braces from a string?

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

Issue

I want to remove everything inside braces. For example, if string is:

[hi] helloz [hello] (hi) {jhihi}

then, I want the output to be only helloz.

I am using the following code, however it seems to me that there should be a better way of doing it, is there?

$name = "[hi] helloz [hello] (hi) {jhihi}";
$new  =  preg_replace("/\([^)]+\)/","",$name); 
$new = preg_replace('/\[.*\]/', '', $new);  
$new = preg_replace('/\{.*\}/', '', $new);  
echo $new;

Solution

This should work:

$name = "[hi] helloz [hello] (hi) {jhihi}";
echo preg_replace('/[\[{\(].*?[\]}\)]/' , '', $name);

Paste it somewhere like: http://writecodeonline.com/php/ to see it work.



Answered By - Damien Overeem
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • 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