1

我如何在 textarea2 中搜索 textarea1 的内容并打印整行匹配

例子:

textarea1 内容(字)

content1
content2
content3

textarea2 内容(行)

this is content1
this is cont
this content3

所以我想要这样的打印匹配线

this is content1
this content 3

因为我的 textarea1 中的 content1 和 content 3

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:此代码遍历干草堆中的所有行并检查其中的每一根针。如果它找到一根针,则通过 echo 打印该行,然后我们继续大海捞针的下一行 - 还有什么需要的吗?

于 2013-06-01T14:11:55.937 回答