开发者

preg_match or eregi questions

开发者 https://www.devze.com 2023-02-16 17:49 出处:网络
i have two questions. 1, i have a input <input name=\"fruit\" type=\"text\" /> i only want to text field to allow 3 kinds of inputs with formats like no space, space and & for example \"

i have two questions.

1, i have a input

<input name="fruit" type="text" />

i only want to text field to allow 3 kinds of inputs with formats like no space, space and & for example "apple", "apple juice" or "apple_juice". how can i achieve this in javascript or php? sorry i am very bad at regex

2, i want to convert the follow s开发者_如何学Pythontring to some formatted string

for example

apple converted to apple

apple juice converted to apple_juice

apple & juice converted to apple_juice

apple&juice converted to apple_juice

apple_juice converted to apple_juice

how can i do this in php?

Thanks for helping me


I don't see a reason why to restrict the input if you convert it to an other format anyway. For example if you have apple + juice, why reject it and not convert it to apple_juice too?

This will convert all consecutive non-alphanumeric characters to one _:

$output = preg_replace('/[\W_-]+/', '_', trim($input));


here's the regex pattern for it /^(apple|apple\sjuice|apple_juice)$/


2.

You seemingly want to replace any non-letter characters with a single _ underscore. This all time classic would do:

$str = preg_replace('/\W+/', "_", $str);
$str = trim($str, "_");   // in case there were any surroundings
0

精彩评论

暂无评论...
验证码 换一张
取 消