1

textarea2 で textarea1 のコンテンツを検索し、一致する行全体を出力する方法

例:

textarea1 内容(単語)

content1
content2
content3

textarea2 内容(行)

this is content1
this is cont
this content3

だから私はこのような印刷されたマッチラインが欲しい

this is content1
this content 3

content1 と content 3 が textarea1 にあるため

4

3 に答える 3

2

を使用した例を次に示しpreg_match()ます。検索文字列は で引用する必要があることに注意してくださいpreg_quote()

$text1 = $_POST['text_area1'];
$text2 = $_POST['text_area2'];

// split search texts. in this case we use new line
$search = explode("\n", preg_quote($text1));

// now prepare for a regex
$regex = '~(' . implode('|', $search) . ')~';

// now split the text by newline
$lines = explode("\n", $text2);

foreach($lines as $line) {
    if(preg_match($regex, $line)) {
        print $line . "\n";
    }   
}

出力:

this is content1
this content3

検索文字列を区切る方法を絞り込むことができることに注意してください。私の例では、改行で分割していますが、さらにスペースで分割したり、,...

于 2013-06-01T13:57:09.310 に答える
0
$textarea1 = "content1\ncontent2\ncontent3";
$chunks = explode("\n", $textarea1);

$textarea2 = "this is content1\nthis is cont\nthis is content3";
$lines = explode("\n", $textarea2);


foreach ($chunks as $c)
    foreach ($lines as $l)
        if (strpos($l, $c))
            echo $l . '<br>';
于 2013-06-01T14:02:59.533 に答える
-2

この場合、正規表現を使用するのは少し多すぎると思います。php が提供する基本的な文字列関数を使用するだけです。

// the \n is the line break smybol used in the textarea
$needle = "content1\ncontent2\ncontent3"; // this text is probably received via $_GET['text1'] or something similar
$haystack = "this is content1\nthis is cont\nthis is content3";

// get all lines
$needle_lines = explode("\n", $needle);
$haystack_lines = explode("\n", $haystack);

foreach($haystack_lines as $hline) {
  foreach ($needle_lines as $line) {
    if (strpos($hline, $line) === false)
      continue;
    echo $hline."<br />";
    //continue the outer foreach since we already found a match for the haystack_line
    continue 2;
  }
}

更新 #1: このコードは、干し草の山内のすべての行を反復処理し、その中のすべての針をチェックします。針が 1 つ見つかった場合、その行はエコー経由で出力され、干し草の山の次の行に進みます。他に何か必要なものはありますか?

于 2013-06-01T14:11:55.937 に答える