Creating an array of cleared tags

On my website, I allow the user to send tags as follows:

tag tagtwo anothertag 

I just want to allow them to use separate spaces and letters, so I want to remove numbers, dashes, double spaces, etc. Thus, an invalid string would be:

 tag tag2 another-tag 

I have the following code for this, but I don't know how to use the regular expression correctly.

 $tags = strtolower($_POST['imgTags']); $tags = preg_replace("/regex/", "", $tags); $tagArray = explode(" ", $tags); 

What is the correct regEx for this? In addition, I might want to replace Γ© and ΓΆ with e and o.

+4
source share
6 answers

This will remove everything except letters and spaces:

 $tags = preg_replace("/[^az ]/i", "", $tags); 

This will then lead to a breakdown of consecutive spaces:

 $tags = preg_replace("/ {2,}/", " ", $tags); 

If you want to allow other types of space characters, but also replace them with single spaces, try this instead:

 $tags = preg_replace("/[^az\s]/i", "", $tags); $tags = preg_replace("/\s+/", " ", $tags); 

Regarding your last sentence: there is no general way to this. You will need to add certain rules. However, preg_replace_callback can help you identify unmodified letters.

+3
source

To use only letters and spaces, use:

 $tags = preg_replace("/[^a-zA-Z\s]/", "", $tags); 

To normalize spaces, add:

 $tags = preg_replace("/\s+/", " ", $tags); 
+1
source

so I want to remove numbers, dashes, double spaces

/([0-9\-]|[\s]{2,})/ should work as a regular expression

+1
source

First of all, replace several spaces and tabs with one:

 /([ \t])[ \t]*/$1/ 

Then replace everything except letters and spaces with zero:

 /[^A-Za-z ]+// 

PHP code

 $tags = preg_replace('/([ \t])[ \t]*/', '$1', $tags); $tags = preg_replace('/[^A-Za-z ]+/', '', $tags); 

Enter

 tag tag2 another-tag 

Output

 tag tag anothertag 
+1
source

That would be simple:

To remove numeric and dashes:

 $tags = preg_replace("/[0-9\-]/", "", $tags); 

Then remove some spaces:

 $tags = preg_replace("/[\s]{2,}/", " ", $tags); 

REGEX DEMO

+1
source

The regular expression will be

 [a-zA-Z ]+ 

This allows uppercase or lowercase letters and a combination of space characters.

0
source

Source: https://habr.com/ru/post/1440261/


All Articles