Re: strip slashes from beginning and end of string in one expression
| From: | M. Sokolewicz | Date: | Thu, 31 Aug 2006 11:38:13 +0000 |
| Subject: | Re: strip slashes from beginning and end of string in one expression | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-241272@lists.php.net to get a copy of this message | ||
Dave M G wrote:
PHP list. This is another regular expression type of question. The very handy PHP function trim() takes excess white space off the beginning and end of a string. I'd like to be able to do the same thing, except instead of white spaces, trim excess slashes: / So for example, all of these: /this/that/ /this/that this/that/ ////////this/that//////////// ... become: this/that There is also the chance of more than one slash occurring inside the desired text: /this/that/this/that/ So that would also need to be accounted for. The above example should become: this/that/this/that I think I need to use preg_replace() for this, but, as ever, regular expressions completely throw me. If I'm not mistaken, "#^/*#" should get me the first slash of the string, and more if there are more. And "#*/$#" should get me the last slash of the string, and more if there are more. Can I test for the first and last slash in the same expression? I think I either need something between the two that says "ignore what's in the middle", or and and/or statement to say "replace if this occurs at the end, or at the beginning, or both". I've looked around and can't seem to find a way of connecting these in the same search. However, I'm sure that is because I'm not familiar enough with regular expressions to know what I'm looking at. How would I connect "#^/*#" and "#*/$#" into one regular expression? Thank you for your time and advice. -- Dave M G Ubuntu 6.06 LTS Kernel 2.6.17.7 Pentium D Dual Core Processor PHP 5, MySQL 5, Apache 2something like $trimmed = preg_replace('#^/*(.+)/*$#m', '$1', $string) should work