Jump to content

Help with regular expressions?


lordbry

Recommended Posts

Hey there, I have a love/hate relationship with regular expressions. I love how powerful they are and hate how mindnumbingly complex they can be to put together. Any help would be greatly appreciated here. I'm trying to do this one thing. If the input string is:

 

    Abc (123 abc stuff) 1xyz

 

I want to strip out the ()'s and everything between them to end up with:

 

    Abc 1xyz

 

Additionally, if there's a way that any of you know how to take this:

 

    ABC ID #: 123456 $123.45

 

... and turn it into this...

 

    ABC $123.45

 

... I would also appreciate that. :) Many many thanks in advance for any help with these issues.

 

- Bry

Link to comment
https://forums.phpfreaks.com/topic/63990-help-with-regular-expressions/
Share on other sites

<?php
$pattern = '/\(.*\)/';
$replace = '';
$string = 'Abc (123 abc stuff) 1xyz';
echo preg_replace($pattern, $replace, $string)
?>

 

Edit, here's the other one

 

<?php
$pattern = '/ID #: [0-9].* /';
$replace = '';
$string = 'ABC ID #: 123456 $123.45';
echo preg_replace($pattern, $replace, $string)
?>

 

Best,

 

Patrick

 

P.S.

 

I think what the previous poster was trying to say is that there is a regex board here where you might get a quicker  response.

You sir are my hero! :) Many thanks!

 

And oddly enough, your solutions actually make sense to me whereas most RegEx patterns I see simply look like gibberish. Sorry about posting in the wrong place. I'll try not to do that again in the future.

 

Thanks!

 

- Bry

For the first, make your quantifier ungreedy (.*?) if the string may contain more than one set of parentheses.

 

For the second, will the ID always be numeric? If so, use \d+. Otherwise, you're matching a starting digit that could be followed by anything.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.