Search code examples
laraveltagsspecial-characters

Delete special characters and blank characters


I use laravel and search for a possibility in the tags to clear all special characters and blank characters before saving and that no empty tags are stored, if only special characters are entered. How can I do that?

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);
        }

Solution

  • With your code, you can use str_replace function for it like this

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