dtl85148 2013-09-05 10:35
浏览 24
已采纳

使用数组中的任何单词拆分字符串

Suppose I have a string like this:

Ch #RoKamb93 ajesop de Bourg #kin #kinnl 9 kunsho taffetas,bunughs rges, note florale,parfaite aseref

My array of delimiters can be :

array('#kin', '#kinnl', '#xxx' );

How can Iparse it to get the Ch #RoKamb93 ajesop de Bourg substring ? Substring just before #kin OR #kinnl

Note: Both #kin OR #kinnl may not present at the same time.

  • 写回答

1条回答 默认 最新

  • duanjiong5023 2013-09-05 10:45
    关注

    How about this:

    $string = 'Ch #RoKamb93 ajesop de Bourg #kin #kinnl 9 kunsho taffetas,bunughs rges, note florale,parfaite aseref';
    
    $delimiters = array('#kin', '#kinnl', '#xxx');
    $pattern = '/' . implode($delimiters, '|') . '/';
    
    $split = preg_split($pattern, $string);
    var_dump($split); // $split[0] has what you need
    

    If your delimiters contain reserved regex characters (like . or ?), you'll need to do something like this for the pattern:

    $pattern = '/' . implode(array_map('preg_quote', $delimiters), '|') . '/';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?