我正在尝试将此 php 函数转换为 javascript:
function sanitize_words($string,$limit=false) {
preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]{1,}/u",$string,$matches,PREG_PATTERN_ORDER);
return $matches[0];
}
基本上,它需要这个字符串:
$string = "Why hello, how are you?"
$array = sanitize_words($string);
并将其转换为数组:
$array[0] = 'Why';
$array[1] = 'hello';
$array[2] = 'how';
$array[3] = 'are';
$array[4] = 'you';
它在 php 上运行得很好,但我不知道如何在 javascript 上实现它,因为 phpjs.org 中没有 preg_match_all 。有任何想法吗?谢谢。
最佳答案
使用String.match
方法,并在正则表达式上设置了 g
(全局)标志。 \w
相当于[a-zA-Z0-9_]
。如果您确实想要模仿当前模式,请使用 this page作为转换 JavaScript 模式中字符属性的引用。
function sanitize_words($string) {
return $string.match(/\w+/g);
}
关于PHP 函数到 Javascript : scan string and add words in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8404557/