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

帮助解析PHP中的字符串

  •  2
  • Ali  · 技术社区  · 14 年前

    我会有这样一个字符串:

    Bob is a boy. Bob is 1000 years old! <b>Bob loves you!</b> Do you love bob?
    

    我想将其解析为一个数组,使用以下分隔符来标识每个数组元素:

    .
    !
    ?
    <b> and </b>
    

    因此,我将有一个数组,其结构如下:

    [0]Bob is a boy.
    [1]Bob is 1000 years old!
    [2]Bob loves you!
    [3]Do you love bob?
    

    有什么想法吗?

    如你所见,我希望 <b> </b>

    preg_match_all(":<b>(.*?)</b>:is", $text, $matches);
    
    3 回复  |  直到 14 年前
        1
  •  2
  •   Alan Christopher Thomas    14 年前

    我认为这应该完成你的目标:

    $string = 'Bob is a boy. Bob is 1000 years old! <b>Bob loves you!</b> Do you love bob?'; 
    
    // parser
    $array = preg_split('/[\.|\!\?]|[\s]*<b>|<\/b>[\s]*/', $string, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
    foreach ($array as $key => $element) $array[$key] = trim($element[0]).substr($string,$element[1]+strlen($element[0]),1);
    
    print_r($array);
    

    它产生:

    Array
    (
        [0] => Bob is a boy.
        [2] => Bob is 1000 years old!
        [4] => Bob loves you!
        [6] => Do you love bob?
    )
    

        2
  •  1
  •   serg    14 年前

    如果没有人能提供更好的解决方案,这几乎是可行的:

    (?:<b>|[.!?]*)((?:[^<]+?)(?:[.!?]+|</b>))\s+
    

    只有它会回来 Bob loves you!</b> strip_tags() 结果我想。。。

        3
  •  1
  •   Zak    14 年前

    分而治之?

    假设$myString是您的字符串。。。

    先拿你的东西:

    preg_match (" /(.*?)<b>(.*?)<\/b>(.*?)/", $myString);
    

    现在你有1美元,2美元和3美元

    $firstMatches = preg_split("/[\.\!\?]/", $1);
    
    $lastMatches = preg_split("/[\.\!\?]/", $3);
    

    然后拿回你的标点符号:

    function addPunctuation($matches, $myString)
    {
        $punctuadedResults = array();
        foreach($matches as $match)
        {
           $position = strpos( $myString, $match);
           #position is the offset of the start of your match. Find the character after your match.
           $punctMark = substr($myString, $position + length($match), 1);
           $punctuadedResults[] = $match . $punctMark;
    
        }
        return $punctuadedResults;
    }
    
    
    $allMatches = addPunctuation($firstMatches, $myString);
    $allMatches[] = $2;
    
    $allMatches = array_merge($allMatches, addPunctuation($lastMatches, $myString) );