【问题标题】:Convert URL to Slug With PHP使用 PHP 将 URL 转换为 Slug
【发布时间】:2014-03-25 08:43:35
【问题描述】:

我正在使用下面的代码尝试转换为 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;
        }

?>

【问题讨论】:

  • 什么是 slug 以及您要覆盖到 slug 中的 URL 在哪里?
  • @Shahar 在WordPress 的说法中,slug 是特定帖子的URL key
  • 你永远不会调用该方法...在底部添加clean($string);

标签: php jquery replace


【解决方案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;

【讨论】:

    【解决方案2】:
    <?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;
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2017-03-31
      • 1970-01-01
      • 2010-11-06
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2023-03-26
      相关资源
      最近更新 更多