Remove Text Between Parenthesis

Discussion in 'PHP' started by belgin fish, Jan 31, 2010.

  1. #1
    Hi, I'm just wondering how I could remove the text between a set of parentheses and the parentheses themselves in php.

    Example :

    ABC (Test1)

    I would like it to delete (Test1) and only leave ABC

    Thanks
     
    belgin fish, Jan 31, 2010 IP
  2. neo1211

    neo1211 Active Member

    Messages:
    52
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    93
    #2
    You could simply use something like:

    
    <?php
    $blah = "ABC (Test1)"; 
    echo substr($blah, 0, strrpos($blah, "("));
    ?>
    
    Code (markup):
     
    neo1211, Jan 31, 2010 IP
  3. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #3
    <?php
    
    $str = 'abc (ABC not happy :( )';
    $str = preg_replace('#\([^\)]*\)#', '', $str);
    echo "$str\n";
    
    ?>
    Code (markup):
     
    joebert, Jan 31, 2010 IP
  4. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #4
    <?php
    
    $text = 'abc (ABC)';
    //this will remove text within brackets.
    $text = preg_replace('#\([a-z0-9]*\)#i', '', $text);
    print $text;
    
    ?>
    PHP:
    or if you'd prefer to replace more precisely, ie. an actual word.

    <?php
    
    $text = 'abc (ABC)';
    $text = str_replace("(ABC)", "", $text);
    print $text;
    ?>
    PHP:
     
    Last edited: Feb 1, 2010
    danx10, Feb 1, 2010 IP
  5. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #5
    <?php
    $string = "ABC (Test1)";
    $string = preg_replace("/\((.*?)\)/", "", $string); // will remove anything between brackets
    echo $string; // prints ABC
    ?>
    PHP:
     
    Bec0de, Feb 1, 2010 IP
  6. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #6
    The reason i added [a-z] was because:

    :p
     
    danx10, Feb 1, 2010 IP
  7. Bec0de

    Bec0de Well-Known Member

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    115
    #7
    (Hello I Own 2 cars) <= That counts a text too :p
     
    Bec0de, Feb 1, 2010 IP
  8. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #8
    True, post edited to also allow numbers.
     
    danx10, Feb 1, 2010 IP
  9. belgin fish

    belgin fish Well-Known Member

    Messages:
    1,544
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    185
    Digital Goods:
    2
    #9
    Thanks guys :)
     
    belgin fish, Feb 1, 2010 IP