JDMallion Posted May 28, 2010 Share Posted May 28, 2010 Am new to regex and am trying to run the following in PHP: $requestUri = preg_replace("/(-|_){2,}/", "_", $requestUri); I need to replace the amount of dashes or underscores found with the same amount of a different value. So for example if it found --_---- it would replace it with __________ but also if it found -- it would replace that with __ I am sure there is a way but I do not know how. Any help would be appreciated. Quote Link to comment Share on other sites More sharing options...
cags Posted May 28, 2010 Share Posted May 28, 2010 You will probably have to use preg_replace_callback to make a callback to count the number of characters in the match and generate another string the same length, perhaps something like str_repeat('_', strlen($match[0])); Quote Link to comment Share on other sites More sharing options...
salathe Posted May 28, 2010 Share Posted May 28, 2010 Or you could just preg_replace('/[-_]/', 'x', $requestUri) (example replaces with x because replacing _ with _ seemed silly). Quote Link to comment Share on other sites More sharing options...
cags Posted May 28, 2010 Share Posted May 28, 2010 @salathe I was going to suggest that, but the original code seems to imply that it should only be replaced if there are two or more of the character present. Granted the example didn't mirror that, but still. I guess it's up to the OP. Quote Link to comment Share on other sites More sharing options...
JDMallion Posted June 1, 2010 Author Share Posted June 1, 2010 @cags Yep, you are correct it is only if there are two or more present, so looks like I will have to go with your option. Was just waiting if there was a way to do it through regular expressions and not use another PHP function. 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.