【问题标题】:PHP function to Javascript: scan string and add words in arrayJavascript的PHP函数:扫描字符串并在数组中添加单词
【发布时间】:2011-12-06 18:04:51
【问题描述】:

我正在尝试将此 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。有任何想法吗?谢谢。

【问题讨论】:

    标签: php javascript regex preg-match-all


    【解决方案1】:

    使用String.match 方法,并在正则表达式上设置g(全局)标志。 \w 等价于 [a-zA-Z0-9_]。如果您真的想模仿当前的模式,请使用this page 作为参考来转换 JavaScript 模式中的字符属性。

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

    【讨论】:

      【解决方案2】:

      JavaScript split() 函数将使用分隔符从任何字符串创建一个数组。在这种情况下,一个空格。

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

      【讨论】:

        【解决方案3】:

        您不需要正则表达式,在 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
        ?>
        

        【讨论】:

        • 好吧,正则表达式去掉了逗号、感叹号等。拆分仍然可以满足我的需要。
        猜你喜欢
        • 2019-07-25
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多