正则表达式与开始标记和结束标记匹配为新行

时间:2011-03-29 09:47:45

标签: php mysql preg-replace

我一直在制作一个信件编制系统(为了节省人们填写问卷后的时间),并且在项目结束时我们发现了一个错误。长话短说,没有这个正则表达式就需要花费很多时间来修复 - 这就是为什么我要求你的帮助!

我们有一些文字包含以下内容......

"<k>This is the start of the paragraph

This is some more of the paragraph.

And some more";

我基本上需要一个可以搜索开始标记的正则表达式“<k>”,以及它遇到的第一个新行“\ r \ n”?然后将内容插入到我可以使用的变量中(删除<k>但新的行代码“\ r \ n”,留在原位)。

我正在使用PHP,文本(如上例所示)存储在MySQL中。

请帮忙!

我保证在修复此错误后我会正确学习这些内容! :)

2 个答案:

答案 0 :(得分:1)

如果你使用5.3,你可以使用这样的闭包:

$text = "<k>This is the start of the paragraph

This is some more of the paragraph.

And some more";

$matches = array();

$text = preg_replace_callback('/<k>(.*)$/m', function($match) use (&$matches){
    $matches[] = $match[1];
}, $text);

var_dump($text,$matches);

输出是:

string '

This is some more of the paragraph.

And some more' (length=52)
array
  0 => string 'This is the start of the paragraph' (length=34)

我假设文本中可能有多个<k>标记,因此,我将标记后面的所有文本放入一个名为matches的数组中。

作为另一个例子......带有以下输入:

$text = "<k>This is the start of the paragraph
Line 2 doesn't have a tag...
This is some more <k>of the paragraph.
Line 4 doesn't have a tag...
<k>And some more";

输出结果为:

string '
Line 2 doesn't have a tag...
This is some more 
Line 4 doesn't have a tag...
' (length=78)
array
  0 => string 'This is the start of the paragraph' (length=34)
  1 => string 'of the paragraph.' (length=17)
  2 => string 'And some more' (length=13)

答案 1 :(得分:0)

/^<k>(\w*\s+)$/

可能会奏效。

相关问题