Neomech Posted September 12, 2009 Share Posted September 12, 2009 Hi, I'm doing some fun things with filters on my site, and I'm trying to use preg_replace to remove a filter from the url when it gets reset in my filter form. Ignoring whether or not I'm going about any of this the right way, I have a strange problem with using preg_replace that I'd like to figure out. I have a string of text like so: "filter1__is__attribute1__and__filter2__is__attribute2__and__filter3__is__attribute3" I'm using preg_replace to remove one of these filters and it's attribute if I find it in the string. The code looks like this: $new_string=preg_replace('/(??:|__and__)(filter__is__.*?__and__))|(?(?:|__and__)filter__is__.*?(?:\/|\z))(?!__and__))/','',$old_string); (I'm replacing the word filter in the above with either filter1, filter2 or filter3 depending on which one I'm trying to replace.) The above code works fine if the filter is at the start or end (filter1 or filter3), but filter2 is borked, because the preg_replace is replacing the "overall" match rather than the specific match, which in that instance is different. In other words, in the filter1 and filter3 position, the "overall" match ($match[0]) is the same as either $match[1] or $match[2], respectively, so preg_replace works fine. In the filter2 position, $match[0] is capturing "__and__filter2__is__attribute2__and__" while the value for $match[1] is "filter2__is__attribute2__and__". Since preg_replace is replacing $match[0] (and therefore replacing that leading "__and__" that I don't want to replace), it messes up my url. I got around this by using a preg_match and then two str_replaces, but I just think I'm doing something wrong in my regular expression, and was wondering if anyone could spot the error easily. Alternatively, if there's a way to use preg_replace to only replace $match[1] or $match[2], but not $match[0], that would help as well. Thanks! p.s. sorry if this is confusing...I've never asked a regex question before and am having difficulty describing it fully without being overly wordy. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.