General / Allgemeines > Programming

working with string patterns...

(1/2) > >>

I am terrible when it comes to string patterns and kind not find the info I need anywhere.
I want to perform a rtrim ($string,"search pattern")  on a string like this one..
$string="This is my data (want to keep this data) (want to delete this data and brackets)"
Anybody have any ideas what my "search pattern" should be to get rid of the second set of () and the data inside it?



Do they mean this?

          $string="This is my data (want to keep this data) (want to delete this data and brackets)";

          preg_match_all('#\([^\)]*\)#', $string, $matches);
          print_R($matches[0][0]."<br>"); //(want to keep this data)
          print_R($matches[0][1]."<br>"); //(want to delete this data and brackets)
          $string = preg_replace('#\('.$matches[0][1].'\)#' ,"",$string);
          print_R($string); //This is my data (want to keep this data) 

or always the last matches:

          $string="This is my data (want to keep this data) (want to delete this data and brackets)";

          preg_match_all('#\([^\)]*\)#', $string, $matches);
          $last_match = array_pop($matches[0]);
          $string = preg_replace('#\('.$last_match.'\)#' ,"",$string);
          print_R($string);//This is my data (want to keep this data) 

mfg Andi

Thanks for the help Rembrandt but I guess I should have been more clear...
The $string variable sometimes will have 2 () in it and sometimes there is only 1().
Mainly, I am wanting to remove the far right set of () and the data inside of it no matter have many () are in the string. On some of them there are 3 sets.
Note, the string will always have a set of () at the end of the string if that helps.

I am glad someone knows more about the patterns because it just confuses me the more I look at it.

When I ran your code on my data, it actually erased the whole string when it only contained one set of ()....

any ideas?

ok, give me some "string" examples, and what you want to remove from their "strings"

Lets see...
"this is test#1 (2012) (delete this data)" needs to become "this is test#1 (2012)"
"this is some data test#2 (data to delete)" needs to become "this is some data test#2"
"this is another test #3 (2012) (september) (get rid of me data)" needs to become "this is another test #3 (2012) (september)"

Hope that makes it a little clearer. The data inside the bracket changes everytime but the brackets are always in the string at the end.
Looking at the rtrim() function looks to me as my best way to go but I can not configure a pattern that would match start bracket, anything in between, end bracket and the end of the string. The rtrim looks like it starts at the end of the string and looks backward when trying to find a match.


[0] Message Index

[#] Next page

Go to full version