Axeia Posted April 28, 2009 Share Posted April 28, 2009 My head hurts from writing this thing: private function convert2regex( $pStr ) { return preg_replace( '~(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\))~', '\\\$0', $pStr ); } But that oughta do the job, right? Took all the characters with a special meaning , escaped them, used the or operator and captured the result to a backreference. Then the backreference is prefixed with a backslash and the preg_replace puts in the proper spot. Quote Link to comment https://forums.phpfreaks.com/topic/155968-converting-a-string-into-a-regular-expression/ Share on other sites More sharing options...
nrg_alpha Posted April 28, 2009 Share Posted April 28, 2009 My head hurts from writing this thing: private function convert2regex( $pStr ) { return preg_replace( '~(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\))~', '\\\$0', $pStr ); } But that oughta do the job, right? Well, without an example string of what you are trying to capture, it's hard to say.. Alternations can be costly.. I would advise a character class instead of all these ORs... return preg_replace( '~([\[^$.|?*+()\\\])~', '\\\$0', $pStr );// hope I didn't miss any characters Perhaps seeing a complete string example before and with the desirable after effects would help illuminate what it is you are trying to accomplish if the above snippet doesn't serve well... Quote Link to comment https://forums.phpfreaks.com/topic/155968-converting-a-string-into-a-regular-expression/#findComment-821166 Share on other sites More sharing options...
Axeia Posted April 28, 2009 Author Share Posted April 28, 2009 Trying to convert basically ANY string into a regular expression. So anything that has a special meaning in a regular expression has to be escaped. Or that was the plan earlier today, using it atm for something a bit less random and so far so good. Quote Link to comment https://forums.phpfreaks.com/topic/155968-converting-a-string-into-a-regular-expression/#findComment-821354 Share on other sites More sharing options...
nrg_alpha Posted April 28, 2009 Share Posted April 28, 2009 You mean using something like preg_quote? Quote Link to comment https://forums.phpfreaks.com/topic/155968-converting-a-string-into-a-regular-expression/#findComment-821371 Share on other sites More sharing options...
Axeia Posted April 29, 2009 Author Share Posted April 29, 2009 Thanks -.- I wonder why that didn't come up when I was searching for an existing solution, checked the php text functions to see if it was there (url_decode etc are, so was expecting this one to be there as well). Quote Link to comment https://forums.phpfreaks.com/topic/155968-converting-a-string-into-a-regular-expression/#findComment-821915 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.