代码之家  ›  专栏  ›  技术社区  ›  slickness

删除特殊字符和空白字符

  •  0
  • slickness  · 技术社区  · 7 年前

    我使用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);
            }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Goms    7 年前

    使用您的代码,您可以使用 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;
           }
        }
    }