Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1139
  • Last Modified:

Regex: remove duplicate slashes [PHP]

I want to get rid of all duplicate slashes, for example:

Hello // world ////, how are/// you?

Should become:

Hello / world /, how are/ you?
0
level9wizard
Asked:
level9wizard
4 Solutions
 
yuk99Commented:
s/\/+//
0
 
marchentCommented:

$str = "Hello // world ////, how are/// you?";
$str = preg_replace('|/+|', '/', $str);
print "$str\n";

Open in new window

0
 
yuk99Commented:
Sorry. s/\/+/\//
0
 
fsze88Commented:
<?
$str = 'Hello // world ////, how are/// you?';

$pattern = '/\/+/';
$replacement = '/';
echo preg_replace($pattern, $replacement, $str);

?>
0
 
FirestormXCommented:
As a quick explanation to what everyone's written above, PHP's regex patterns are simply strings, with a / at the begining and end of the pattern, which is why they're putting a \ in front of the /, to "escape" the character. So baiscally /\/+\//, actually becomes a pattern of /+/

Then + sign means to look for 1 or more instance of the previous character, which in this case, is /. It then checks to see if after it finds as many of / as possible, to make sure the last character is /.  
So translated, it means "find one or more /, that ends in /, and replace everything it finds with a single /".
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now