【问题标题】:Remove line with one or two digits using php使用php删除一位或两位数字的行
【发布时间】:2015-10-24 13:29:56
【问题描述】:

我试图删除包含一两个字符的行。

例如:

text text
11
0
text

结果:

text text
text

我使用了$text = str_replace('/^(.{2})', 'dsfsdfsd', $text);,但不起作用。

怎么了?

【问题讨论】:

  • 你必须检查你的正则表达式。您指定的正则表达式匹配字符串的开头,后跟两个字符,没有限制。您必须构建更精确的正则表达式并根据需要调整匹配行为。有很多工具可用于帮助编写正则表达式,例如 regex101.com

标签: php regex replace


【解决方案1】:

str_replace 不接受正则表达式。这是一个针/大海捞针搜索和替换功能。这意味着它寻找字符串 literal

对于正则表达式搜索/替换,请改用preg_replace

例如,如果您想删除恰好包含 1 位或 2 位数字的任何文本行,您可以将以下正则表达式与 preg_replace 结合使用。

$text = '
text text
11
0
text
';

$text = preg_replace('/^\d{1,2}$/m', '<replaced>', $text);

echo $text;
/**
 * This should give you ...
 * 
 * text text
 * <replaced>
 * <replaced>
 * text
 */

这里的\d 表示PCRE 中的任何数字字符[0-9],括号内的{1,2} 仅表示匹配1 位或2 位字符。从此表达式中删除插入符号和符号会使其匹配主题中找到的任何 1 或 2 位字符表达式。在这里,它在 m 模式修饰符允许 PCRE 引擎进入多行模式的每一行上查找完全匹配。您还可以阅读有关PCRE pattern syntax in the manual 的更多信息。

【讨论】:

    【解决方案2】:

    preg_replace("/[a-zA-Z0-9]{1,2}/i", 'sometext', $text);

    【讨论】:

      【解决方案3】:

      正如其他人建议的那样,对于正则表达式,您需要使用preg_replace。下面的示例非常适合您的输入。

      <?php
          $text = "Lorem Ipsum\nDolar\n2\nContan\n23";
          $after = preg_replace("/[\n][0-9]{1,2}[\n]{0}/", "", $text);
          echo "<pre>";
          echo "Before : \n".$text."\n\n";
          echo "After : \n".$after;
      ?>
      

      【讨论】:

        【解决方案4】:

        在正则表达式中数字用d表示(包括所有语言),否则可以使用[0-9]{2}\d{2}

        【讨论】:

        • str_replace 不使用正则表达式并且用户要求输入字符
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 2012-06-02
        • 2019-03-08
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        相关资源
        最近更新 更多