使用PHP将URL转换为Slug

时间:2014-02-23 21:46:41

标签: php jquery replace

我正在使用下面的代码尝试转换为slug,由于某种原因,它没有回应任何东西。我知道我错过了一些非常明显的东西。我不是在调用这个函数吗?

<?php 

        $string = "Can't You Convert This To A Slug?";

        function clean($string) {
           $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
           return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
           echo $string;
        }

?>

2 个答案:

答案 0 :(得分:1)

在代码退出函数后回显。

尝试这样:

 function clean_string($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
 }

$some = clean_string("Can't You Convert This To A Slug?");

echo $some;

或者像这样:

 function clean_me(&$string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
 }

$some = "Can't You Convert This To A Slug?";

clean_me($some);

echo $some;

答案 1 :(得分:1)

<?php

        $string = "Can't You Convert This To A Slug?";

        function clean($string) {
           $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
           return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
        }

        $string = clean($string);
        echo $string;
?>