Skip to main content
pearl_jan
Participating Frequently
July 12, 2016
Answered

PHP - Replace forward slash (/) with dash (-)

  • July 12, 2016
  • 1 reply
  • 26508 views

I started out wanting to replace spaces, special characters etc. with dashes. However, I can't seem to find the right way to replace a forward slash with a dash. I've looked all over the internet, some people suggesting using the .htaccess-file though I don't think that fits my purpose. My coding so far:

Example: You've got 1 new message (12/07/2016)

As I would like to have it: you-ve-got-1-new-message-12-07-2016

<?php

$message_original = $row_message ['title'];

$message_lower = strtolower($message_original);

$message_alpha = preg_replace("/[^a-z0-9_\s-]/", "", $message_lower);

$message_dash = preg_replace("/[\s-]+/", " ", $message_alpha);

$message = preg_replace("/[\s_]/", "-", $message_dash);

?>

This topic has been closed for replies.
Correct answer David_Powers

$string = "You've got 1 new message \$! (12/07-2016)";

$filtered = strtolower(preg_replace('/[\W\s\/]+/', '-', $string));

echo $filtered;  // you-ve-got-1-new-message-12-07-2016

You can do it with the simplified code above. The regular expression '/[\W\s\/]+/' is a pattern group that contains three metacharacters:

  • \W matches any character that isn't alphanumeric or the underscore (it's the same as [^A-Za-z0-9_]).
  • \s matches any whitespace character.
  • \/ matches a forward slash.

1 reply

David_Powers
David_PowersCorrect answer
Inspiring
July 12, 2016

$string = "You've got 1 new message \$! (12/07-2016)";

$filtered = strtolower(preg_replace('/[\W\s\/]+/', '-', $string));

echo $filtered;  // you-ve-got-1-new-message-12-07-2016

You can do it with the simplified code above. The regular expression '/[\W\s\/]+/' is a pattern group that contains three metacharacters:

  • \W matches any character that isn't alphanumeric or the underscore (it's the same as [^A-Za-z0-9_]).
  • \s matches any whitespace character.
  • \/ matches a forward slash.