slickness
slickness

Reputation: 246

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

Upvotes: 0

Views: 393

Answers (1)

Goms
Goms

Reputation: 2644

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

Upvotes: 1

Related Questions