joe92 Posted January 28, 2012 Share Posted January 28, 2012 I wish to extract the data between the square brackets and replace the spaces with underscores in one go? E.g. I have the string location=[location to go to] I need to get it to, location_to_go_to Currently I am using a preg_replace_callback with a str_replace to change the spaces into underscores, but it seems like a long winded route to take. Is there a way I can do this in one clean sweep of a preg_replace? Here is the existing code: <?php function removeSpace($match){ $string = $match[1]; $string = str_replace(' ', '_', $string); return $string; } $location = 'location=[location to go to]'; echo $location.'<br/>into<br/>'; $location = preg_replace_callback("~location=\[([\w\s-]+)\]~ism", "removeSpace", $location); echo $location; If not, then I suppose it's no great loss. I'm just constantly looking for ways to improve my regex skills Cheers, Joe Quote Link to comment Share on other sites More sharing options...
ragax Posted January 28, 2012 Share Posted January 28, 2012 Hi Joe, You don't know the number of spaces (if any) in the string, is that right? If so, your preg_replace_callback combined with a str_replace or preg_replace looks great to me. If you know the number of spaces, you can do it with a single preg_replace, but you probably know that. Wishing you a fun weekend. Quote Link to comment Share on other sites More sharing options...
joe92 Posted January 28, 2012 Author Share Posted January 28, 2012 Could be no spaces, could be over a dozen spaces, haha. Oh well, thanks for taking the time to respond. Joe 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.