duanjing1023 2009-10-07 11:17
浏览 26
已采纳

另一个preg_replace问题!

Ive got a string that are words bunched together and I need to seperate them, and every word that ends in 'A' should probably be on a new line,

item onea second itema third

I also need to check if the word ending in 'A' should actually end in 'A' like extra or sultana.

item oneasecond itemand an extra item

I have an array full of words ending in 'A' from this website http://www.morewords.com/ends-with/a so I just need the preg_replace function.

I really am learning everytime someone answers a question here so again thanks for everyones time and patience

  • 写回答

4条回答 默认 最新

  • doulan8054 2009-10-07 12:08
    关注

    You could do something like this:

    // assoc array keyed on words that end with A
    $endsWithA = array("sultana" => 1, ...); 
    
    $words = split(' ', $string);
    
    $newString = '';
    $finalStrings = array();
    
    foreach ($words AS $w) {    
        // if it ends with a, check to see if it's a real word.
        // if so, end the current string and store it
        if (preg_match("/a$/", $w) && !$endsWithA[$w]) {
            $w = preg_replace("/a$/","", $w);
            $newString .= $w;
            $finalStrings[] = $newString;
            $newString = '';
        }
        else {
            $newString .= $w . ' ';
        }    
    }
    
    // Get any remaining newString
    if ($newString) $finalStrings[] = trim($newString);
    
    print_r($finalStrings);
    

    Haven't tested it, etc., but it would give you an array $finalStrings populated with the strings split from the original.

    Update: fixed a couple of typos in the code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起