Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

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

New Here ,
Jul 12, 2016 Jul 12, 2016

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);

?>

TOPICS
Code , How to , Server side applications
26.0K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

LEGEND , Jul 12, 2016 Jul 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.
Translate
LEGEND ,
Jul 12, 2016 Jul 12, 2016
LATEST

$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.
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines