【问题标题】:Regular Expression matching with start tag and closing tag as a new line正则表达式与开始标记和结束标记匹配为新行
【发布时间】:2011-07-25 03:31:42
【问题描述】:

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

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

"<k>This is the start of the paragraph

This is some more of the paragraph.

And some more";

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

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

请帮忙!

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

【问题讨论】:

    标签: php mysql preg-replace


    【解决方案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)
    

    我假设文本中可能有多个&lt;k&gt; 标签,因此,我将标签后面的所有文本放入一个名为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)
    

    【讨论】:

    • 感谢 Jacob :) 正是我所需要的。
    【解决方案2】:
    /^<k>(\w*\s+)$/
    

    可能会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多