Javascript的PHP函数:扫描字符串并在数组中添加单词

PHP function to Javascript: scan string and add words in array

本文关键字:串并 数组 单词 添加 字符串 字符 PHP 函数 扫描 Javascript      更新时间:2023-09-26

我正在尝试将这个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方法,在RegEx上设置g(全局)标志。'w等于[a-zA-Z0-9_]。如果你真的想要模仿你当前的模式,使用该页作为参考来转换JavaScript模式中的字符属性。

function sanitize_words($string) {
    return $string.match(/'w+/g);
}

JavaScript split()函数将使用分隔符从任何字符串生成数组。在本例中,空格

var str = "Why hello, how are you?".split(" ")
alert(str[0]) // = "Why"

你不需要正则表达式,在javascript中分割就可以了。

<script type="text/javascript">
var myString = "zero one two three four";
var mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

显示:

Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four 

作为一个旁注,在你的PHP脚本中,如果你想做的只是创建一个词数组,你应该使用explode(),它有一个更少的开销:

<?php
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
// to remove non alpha-numeric chars, and still less costly
$pizza = preg_replace('/[^a-zA-Z0-9's]/', '', $pizza);
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>