JS Regexp替换“非法”字符来创建PHP函数名称

时间:2011-08-25 16:06:32

标签: javascript regex

我正在尝试使用此正则表达式从URL生成PHP函数名称(取自PHP Manual - User-defined functions

url = "controller/action,/param";
re = /[^a-zA-Z0-9_\x7f-\xff]*/g; // consecutive characters that are not in range
result = url.replace(re, "_");

我希望结果为controller_action_param(单个下划线),但我得到的结果是:_c_o_n_t_r_o_l_l_e_r__a_c_t_i_o_n__p_a_r_a_m_

我认为这在某种程度上与UTF-8 / Unicode有关,但不应该\x7f-\xff部分处理它吗?

JsFiddle Example

3 个答案:

答案 0 :(得分:5)

*更改为+*匹配前面字符的零或更多,您希望一个或多个

re = /[^a-zA-Z0-9_\x7f-\xff]+/g;

答案 1 :(得分:2)

丢失*(提示:它匹配0个字符),改为使用+

re = /[^a-zA-Z0-9_\x7f-\xff]+/g; 

答案 2 :(得分:2)

使用+(1或更多)代替*零或更多。

re = /[^a-zA-Z0-9_\x7f-\xff]+/g;