2017-06-15 13 views
1

私は初心者をコードするPHPですので、最初と3番目のマッチを出力したいと思います。以下のコードはこれまでのコーディングです。PHPの出力pre_replace_callback

$string="[nextpage] This is first text 
[nextpage] This is the second text 
[nextpage] This is the third text"; 
$string = preg_replace_callback("/\[nextpage\]([^\[nextpage\]]*)(.*?)(\n|\r\n?)/is", function ($submatch) { 
    static $matchcount = 0; 
    $matchcount++; 
    $rtt=$submatch[2]; 
    return "<li>$rtt</li>"; 
    }, $string); 
echo $string; //This is first text 
       This is the second text 
       This is the third text 

私は、第三試合を得るために、最初に一致し、$rtt=$submatch[0][3];を取得するために$rtt=$submatch[0][1];を出力しようとしましたが、動作しません。

予想される結果。

//This is first text 
    This is the third text 

答えて

1

あなたは$matchcountを使用して一致するものをテストしていません。

また、\r\nとのマッチングは、改行がないため、最後の行の末尾と一致しません。また、文字列の最後である$と一致する必要があります。

([^\[nextpage\]]*)はまったく必要ではないと思われることはありません。 [^string]は、その文字列と一致しないことを意味するものではなく、それらの文字ではない単一の文字と一致します。

$string = preg_replace_callback("/\[nextpage\]([^\r\n]*)(\n|\r\n?|$)/is", function ($submatch) { 
    static $matchcount = 0; 
    $matchcount++; 
    if ($matchcount == 1 || $matchcount == 3) { 
     $rtt=$submatch[1]; 
     return "<li>$rtt</li>"; 
    } else { 
     return ""; 
    } 
    }, $string); 

DEMO

+0

感謝を生み出します。これは私の問題を解決しました。 – Omotayo

+0

@barmarどうすれば 'count($ submatch)'を試した正規表現の総マッチを得ることができますが動作しません。 – Omotayo

+0

'$ matchcount'をグローバル変数にすることができます。それは、マッチの数を含みます。 – Barmar

0

たぶん異なるアプローチが順序でありますか?

文字列を配列に分割し、気になる部分を選択することができます。

<?php 
$string="[nextpage] This is first text 
[nextpage] This is the second text 
[nextpage] This is the third text"; 

$explosion = explode('[nextpage] ', $string); 
var_dump($explosion); 
$textICareAbout = trim($explosion[1]) . " " . trim($explosion[3]); 

echo $textICareAbout; 

貢献のため

array(4) { 
    [0]=> 
    string(0) "" 
    [1]=> 
    string(20) "This is first text 
" 
    [2]=> 
    string(25) "This is the second text 
" 
    [3]=> 
    string(22) "This is the third text" 
} 

This is first text This is the third text 
+0

私は出力を 'preg_replace_callback'の中に入れたいのですが、これは他のものの出力を使うためです。とにかく、@ Barmarの答えは私の問題を解決しました。貢献に感謝します。 – Omotayo