首页 > 解决方案 > Exclude special characters from title to use it as a file name?

问题描述

In laravel 5.8 I need to write some content from DB to files on disks where the name of the file would be title field and I wonder how can I remove special characters from the title?

The title field is text English commonly but can contain digits or maybe different chars like “&amp;^<”.

Does laravel/PHP have any method to remove these special characters?

Ubuntu 18, LAMP, php 7.2 used.

标签: laravel-5

解决方案


You can use regular expression for this task. There is a method preg_replace in PHP which works with regular expression.

$title = preg_replace("/[^A-Za-z0-9 ]/", '', $title);

It will replace all non-alphanumeric characters from your title.

If you want to exclude numeric character then you can modify it to

$title = preg_replace("/[^A-Za-z ]/", '', $title);

Hope it will help :)


推荐阅读