开发者

How to get only from string using javascript or PHP?

I have a problem to extract only 'a-zA-Z0-9- _' from string.

Example;

If i input "A cat นกห 004-1 กกกกก" it show me only 'a-cat-0开发者_如何学编程04-1'

or

if i input "aa مقتطف 4-5 aaa" --> 'aa-5-4-aaa'

any idea?


Do the following:

  • Replace [^a-zA-Z0-9_ -] by nothing. This eliminates any characters you don't want.
  • Trim whitespace from the start and end of the string.
  • Replace ' +' (one or more spaces) by -
  • Convert the string to lower-case.

At least that's what I can guess what you want there. Your examples don't match your problem description. The part about the spaces and lower-case was inferred from your examples since you didn't mention it.

In PowerShell this might look like the following:

PS> (('A cat นกห 004-1 กกกกก' -replace '[^a-zA-Z0-9_ -]').Trim() -replace ' +','-').ToLower()
a-cat-004-1

PS> (('aa مقتطف 4-5 aaa' -replace '[^a-zA-Z0-9_ -]').Trim() -replace ' +','-').ToLower()
aa-4-5-aaa

Adapt accordingly for PHP or Javascript. Both support regular expressions and string functions.


preg_replace('/[^a-zA-Z0-9- _]/u', "", $original);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜