Lucas
Lucas

Reputation: 3715

Removal of special characters, a comma separated text, PHP

I got my text variable which is user-specified, normally, user should enter the tags which has to look following:

"food, community, relationship"

but if user type for example

"food;;[]'.'.;@$#community,,,-;,,,relationship"

the script should change it into:

"food, community, relationship".

How can I get this done?

Upvotes: 0

Views: 1737

Answers (3)

Toto
Toto

Reputation: 91373

how about:

$str = "-----music,,,,,,,,games;'235@#%@#%media";
$arr = preg_split("/\W+/", $str, -1, PREG_SPLIT_NO_EMPTY);
$str = implode(', ', $arr);
echo $str,"\n";

output:

music, games, 235, media

You could adapt the \W to which characters you need to keep.

Upvotes: 4

TJHeuvel
TJHeuvel

Reputation: 12608

You could replace everything that isnt alphanumeric, as such:

preg_split('/\W+/','',$input);

will output

Array ( [0] => food [1] => community [2] => relationship [3] => 1123123123 )

Edit: fixed regex

Upvotes: 0

trampi
trampi

Reputation: 2284

You could use something like this:

$content = preg_replace("/[a-zA-Z,]/", "", $content);
$content = str_replace(",,", ",", $content);
$content = str_replace(",", " ,", $content);

Upvotes: 0

Related Questions