Yii - Make a string usable in a URL or filename

情到浓时终转凉″ 提交于 2019-12-24 02:56:05

问题


Does the Yii framework contain a function that can make a string usable in a URL or filename ?

For example: Health+%26+Safety+franchises = health-safety-franchises

So something similar to: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#slugify


回答1:


slugify in Django Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.
Following are the functions in PHP to carry out same tasks.

$slug = preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $str);
      //this will replace all non alphanumeric char with '-'
$slug = mb_strtolower($slug);
      //convert string to lowercase
$slug = trim($slug, '-');
      //trim whitespaces

You need to define a function in some controller TO use it in Yii




回答2:


It is still not completely clear what you are trying to achieve exactly. If you want to use a string that contains characters that are not supported by the browser then you should look into php functions that can do this for you.

Perhaps http://php.net/manual/en/function.urlencode.php (there are more, depends what you need)

If you want to use your own custom encoding then specify what your trying to achieve and I might be able to help.




回答3:


You can add a behaviour to a model for that - this plugin will do the hard work for you.




回答4:


Have a look to this class into yii2

https://github.com/yiisoft/yii2/blob/master/framework/behaviors/SluggableBehavior.php

and see how it use this library http://www.yiiframework.com/doc-2.0/yii-helpers-inflector.html the slug method



来源:https://stackoverflow.com/questions/9199154/yii-make-a-string-usable-in-a-url-or-filename

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!