代码之家  ›  专栏  ›  技术社区  ›  Omotayo

PHP用正则表达式匹配新行中的所有字符

  •  2
  • Omotayo  · 技术社区  · 7 年前

    我想匹配之后的任何字符 [nextpage]

    $string="[nextpage] This is how i decided to make a living with my laptop.
    This doesn't prevent me from doing some chores,
    
    I get many people who visits me on a daily basis.
    
    [nextpage] This is the second method which i think should be considered before taking any steps.
    
    That way does not stop your from excelling. I rest my case.";
    
    $pattern="/\[nextpage\]([^\r\n]*)(\n|\r\n?|$)/is";
    preg_match_all($pattern,$string,$matches);
    $totalpages=count($matches[0]);
    $string = preg_replace_callback("$pattern", function ($submatch) use($totalpages) { 
    $textonthispage=$submatch[1];
    return "<li> $textonthispage";
    }, $string);
    echo $string;
    

    这只返回第一行中的文本。

    <li> This is how i decided to make a living with my laptop.
    
    <li> This is the second method which i think should be considered before taking any steps.
    

    预期结果;

    <li> This is how i decided to make a living with my laptop.
    This doesn't prevent me from doing some chores,
    
    I get many people who visits me on a daily basis.
    
    <li> This is the second method which i think should be considered before taking any steps.
    
    That way does not stop your from excelling. I rest my case.
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   anubhava    7 年前

    \[nextpage]\h*(?s)(.+?)(?=\[nextpage]|\z)
    

    替换为:

    <li>$1
    

    RegEx Demo

    PHP代码:

    $re = '/\[nextpage]\h*(?s)(.+?)(?=\[nextpage]|\z)/';
    $result = preg_replace($re, '<li>$1', $str);
    

    Code Demo

    正则表达式分解:

    \[nextpage]         # match literal text "[nextpage]"
    \h*                 # match 0+ horizontal whitespaces
    (?s)(.+?)           # match 1+ any characters including newlines
    (?=\[nextpage]|\z)  # lookahead to assert that we have another "[nextpage]" or end of text
    
        2
  •  0
  •   Martijn    7 年前

    如果你有一个固定的字符串,你不应该正则表达式。正则表达式很昂贵,简单的str_替换也能实现这一目的:

    $result = str_replace("[nextpage]", "<li>", $str);
    

    如果您想将其作为适当的HTML,还需要一个关闭标记:

    $result = str_replace("[nextpage]", "</li><li>", $string);
    $result = substr($result, 5, strlen($result)).'</li>'; // remove the start </li>
    
    echo $result;