2017-02-01 7 views
0

これは実際には2つのSO質問split string into words by using space a delimiterSplit string by other stringsの組み合わせの1つですが、解決策には直面しましたが解決策が見つかりませんでした。PHP:異なる区切り文字のリストを含む分割文字列と区切り文字についての情報を保持

のは、区切り文字の配列は、それが

$text == $delimiterArr[0] . $textArr[0] . $delimiterArr[1] . $textArr[1] . ... . $delimiterArr(count($delimiterArr)); 

P.S.ことは事実である別の言葉で

$splitby = array('dlmtr1','dlmtr2','dlmtr3',' ','dlmtr5','dlmtr6'); 

$text = ' dlmtr1This is  the string dlmtr2dlmtr2TTTdlmtr5WWWWW '; 


$textArr = ('This', 'is', 'the', 'string', 'TTT', 'WWWWW'); 

$delimiterArr = (' dlmtr1', ' ', '  ', ' ', 'dlmtr2dlmtr2', 'dlmtr5',' '); 

あるとしましょう結果として、$delimiterArrの各項目には、少なくとも1つまたは複数の区切り文字が表示されます。

パターンのための可能な解決策の手順は次のとおりです。

$pattern = '/\s?'.implode($splitby, '\s?|\s?').'\s?/'; 

は、それから私は私が続けるどのような方法で間違った結果を取得します。

アップデート:ここで私は近いと予想結果とが、問題は区切り文字が分割されているが、それらはテキストで一緒にされている場合、彼らは一緒に来る必要があります**

$splitby = array('dlmtr1','dlmtr2','dlmtr3',' ','dlmtr5','dlmtr6'); 
$text = ' dlmtr1This is  the string dlmtr2dlmtr2TTTdlmtr5WWWWW '; 

$pattern = '/\s?'.implode($splitby, '\s?|\s?').'\s?/'; 
$result = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY); 
preg_match_all($pattern, $text, $matches); 
print_r($result); 
print_r($matches[0]); 
を持っているものです

結果:

Array 
(
    [0] => This 
    [1] => is 
    [2] => the 
    [3] => string 
    [4] => TTT 
    [5] => WWWWW 
) 
Array 
(
    [0] => 
    [1] => dlmtr1 '[0] and [1] should come together 
    [2] => 
    [3] =>  
    [4] => 
    [5] => 
    [6] => dlmtr2 '[6] and [7] should come together 
    [7] => dlmtr2 
    [8] => dlmtr5 
    [9] => 
) 

ありがとうございました。

+0

Downvoter、あなたの投票を説明してください。ありがとうございました。 – Haradzieniec

答えて

1

以下のコードは、期待通りに動作します。

$splitby = array('dlmtr1','dlmtr2','dlmtr3',' ','dlmtr5','dlmtr6'); 
$text = ' dlmtr1This is  the string dlmtr2dlmtr2TTTdlmtr5WWWWW '; 

preg_match_all("/\s*(dlmtr[1-6])+\s*|\s+/", $text, $matches); 
echo "<pre>";print_r($matches[0]);echo "</pre>"; 

Array 
(
    [0] => dlmtr1 
    [1] => 
    [2] =>  
    [3] => 
    [4] => dlmtr2dlmtr2 
    [5] => dlmtr5 
    [6] => 
) 

$result = explode(' ', trim(preg_replace("/\s*(dlmtr[0-9])+\s*|\s+/",' ', $text))); 
echo "<pre>";print_r($result);echo "</pre>"; 

Array 
(
    [0] => This 
    [1] => is 
    [2] => the 
    [3] => string 
    [4] => TTT 
    [5] => WWWWW 
) 
関連する問題