Splitting string containing letters and numbers not separated by any particular delimiter in PHP

后端 未结 2 630
太阳男子
太阳男子 2021-01-05 11:36

Currently I am developing a web application to fetch Twitter stream and trying to create a natural language processing by my own.

Since my data is from Twitter (lim

相关标签:
2条回答
  • 2021-01-05 12:01

    how about this:

    you extract numbers from string by using regexps, store them in an array, replace numbers in string with some kind of special character, which will 'hold' their position. and after parsing the string created only by your special chars and normal chars, you will feed your numbers from array to theirs reserved places.

    just an idea, but imho might work for you.

    EDIT: try to run this short code, hopefully you will see my point in the output. (this code doesnt work on codepad, dont know why)

    <?php
    $str = "Hi, my name is Bob. I m 19yo and 170cm tall";
    preg_match_all("#\d+#", $str, $matches);
    $str = preg_replace("!\d+!", "#SPEC#", $str);
    
    print_r($matches[0]);
    print $str;
    
    0 讨论(0)
  • 2021-01-05 12:17

    You can use preg_split

    $string = "Hi, my name is Bob. I m 19yo and 170cm tall";
    $parts = preg_split("/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i", $string);
    var_dump ($parts);
    

    When matching against the digit-letter boundary, the regular expression match must be zero-width. The characters themselves must not be included in the match. For this the zero-width lookarounds are useful.

    http://codepad.org/i4Y6r6VS

    0 讨论(0)
提交回复
热议问题