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_juicehow 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
精彩评论