代码之家  ›  专栏  ›  技术社区  ›  chaimp

字符串中的PHP标记

  •  3
  • chaimp  · 技术社区  · 14 年前

    假设您有一个这样的字符串: token1 token2 tok3

    您希望获得所有的标记(特别是空格之间的字符串),以及它们的位置(偏移量)和长度。

    所以我想要一个这样的结果:

    array(
        array(
            'value'=>'token1'
            'offset'=>0
            'length'=>6
        ),
        array(
            'value'=>'token2'
            'offset'=>7
            'length'=>6
        ),
        array(
            'value'=>'tok3'
            'offset'=>14
            'length'=>4
        ),
    )
    

    我知道这可以通过简单地循环字符串中的字符来完成,我可以简单地编写一个函数来完成。

    我想知道,PHP是否有任何内置的功能可以有效地完成这一任务,或者至少有助于实现这一目标?

    我正在寻求建议,并感谢您提供的任何帮助。谢谢

    4 回复  |  直到 6 年前
        1
  •  4
  •   Gumbo    14 年前

    preg_match_all

    $str = 'token1 token2 tok3';
    preg_match_all('/\S+/', $str, $matches, PREG_OFFSET_CAPTURE);
    var_dump($matches);
    

    $matches[0]

    function update($match) {
        return array( 'value' => $value[0], 'offset' => $value[1], 'length' => strlen($value[0]));
    }   
    array_map('update', $matches[0]);
    var_dump($matches[0]);
    
        2
  •  4
  •   Surreal Dreams    14 年前

    tokena tokenb tokenc

    $tokens = explode(' ', $data);
    

    strlen($tokens[$index]); $token_count = count($tokens);

        3
  •  1
  •   Bojangles Vincent Baillet    14 年前

    explode() strlen()

    explod() foreach() for()

        4
  •  0
  •   chaimp    14 年前

    function get_words($string) {
        $string_chars = str_split($string);
    
        $words = array();
        $curr_offset = 0;
    
        foreach($reduced_string_chars as $offset=>$char) {
            if ($char == ' ') {
                if ($length) $words[] = array('offset'=>$curr_offset,'length'=>$length,'value'=>implode($value_array));
    
                $curr_offset = $offset;
                $length = 0;
                $value_array = array();
            }
            else {
                $length++;
                $value_array[] = $char;
            }
    
        }
    
        return $words;
    }