删除特殊字符和空白字符

Delete special characters and blank characters

我使用 laravel 并在标签中搜索在保存前清除所有特殊字符和空白字符的可能性,如果只输入特殊字符,则不会存储空标签。我该怎么做?

if($product)
        {
            $tagNames = explode(',' ,$request->get('itag'));
            $tagIds = [];
            $toReplace = ['%', ' ', '_', '?', '&', '#', '$', '!', '"', '/', '(', ')', '=', '{', '}', '[', ']'];
            foreach($tagNames as $tagName)
            {
                $tag = Tag::firstOrCreate(['name' => str_replace($toReplace, '', $tagName)]);

                if ($tag) {
                    $tagIds[] = $tag->id;
                }
            }
            $interest->tags()->sync($tagIds);
        }

使用您的代码,您可以像这样使用 str_replace 函数

$toReplace = ['%', ' ', '_', '?', '&'];
foreach($tagNames as $tagName)
{
    if(!empty(str_replace($toReplace, '', $tagName))){
        $tag = Tag::firstOrCreate(['name'=>str_replace($toReplace, '-', $tagName)]);
       if($tag)
       {
          $tagIds[] = $tag->id;
       }
    }
}