删除特殊字符,逗号分隔文本,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?
我得到了用户指定的文本变量,通常,用户应输入必须符合以下内容的标记: p>
“food,community,relationship”
code> pre>
但如果用户输入例如 p>
“食品;; []; @ $#社区,,, '' - ; ,,,关系”
代码> PRE>
脚本应该将其更改为: p>
“food,community,relationship”。
code> pre>
我怎样才能获得 这样做了吗? p>
div>
答
how about:
$str = "-----music,,,,,,,,games;'235@#%@#%media";
$arr = preg_split("/\W+/", $str, -1, PREG_SPLIT_NO_EMPTY);
$str = implode(', ', $arr);
echo $str,"
";
output:
music, games, 235, media
You could adapt the \W
to which characters you need to keep.
答
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
答
You could use something like this:
$content = preg_replace("/[a-zA-Z,]/", "", $content);
$content = str_replace(",,", ",", $content);
$content = str_replace(",", " ,", $content);