使用php删除带有一个或两个数字和空格的行

时间:2015-10-24 16:53:09

标签: php regex forms

我想删除只包含一位数字,2位数字,一位数字,一位数字的行。

例如:

text 1
1 text
11
1 0
111
1 

修改于:

text 1
1 text
111

我的代码是:

<?php
if(isset($_POST["submit"])) 
{
    $text = $_POST["edit"];
    $text = preg_replace('/^\d{1,2}$/m', 'change', $text);
}
?>
<form id="form1" name="form1" method="post" action="">
    <input style="display:block;" type="submit" name="submit" id="submit" value="Submit" />
    <textarea name="edit" id="edit" cols="75" rows="30">
    </textarea>
    <textarea cols="75" rows="30">
        <?php echo $text; ?>
    </textarea>
</form>

http://phpfiddle.org/main/code/cyba-98fj

问题是只有最后一行有一两个数字。

我该怎么办?

3 个答案:

答案 0 :(得分:1)

你可以试试这个正则表达式:

(?:^|\n)\d?\s?\d?(?=\n|$)

Regex live here.

(?:^|\n)      # at start or at new lines
\d?           # optional digit
\s?           # optional space
\d?           # optional digit
(?=\n|$)      # must be the end or a new line

希望它有所帮助。

答案 1 :(得分:1)

如果您有多行文字,请使用

^\d(?:\h?\d)?$\n?

正则表达式分解:

  • ^ - 行首
  • \d - 一位数
  • (?:\h?\d)? - 1或0个水平空格(\h?)和一个数字(\d)的可选(1或0次)序列
  • $ - 行尾
  • \n? - 可选的换行符号。

请参阅regex demo

$re = '/^\d(?:\h?\d)?$\n?/m'; 
$str = "text 1\n1 text\n11\n1 0\n111\n1"; 
echo $result = preg_replace($re, "", $str);

请参阅IDEONE demo

答案 2 :(得分:0)

<?php

$text = <<< LOL
text 1
1 text
11
1 0
111
1 
LOL;
$text = preg_replace('/^(\d{1,2}|\d\s{1}\d?)$/sim', '', $text);
//remove blank lines
$text  = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $text );

echo $text;
/*
text 1
1 text
111
*/

<强>样本

http://ideone.com/THEkbz

正则表达式解释

^(\d{1,2}|\d\s{1}\d?)$

Options: Case insensitive; Exact spacing; Dot matches line breaks; ^$ match at line breaks; Greedy quantifiers; Regex syntax only

Assert position at the beginning of a line «^»
Match the regex below and capture its match into backreference number 1 «(\d{1,2}|\d\s{1}\d?)»
   Match this alternative «\d{1,2}»
      Match a single character that is a “digit” «\d{1,2}»
         Between one and 2 times, as many times as possible, giving back as needed (greedy) «{1,2}»
   Or match this alternative «\d\s{1}\d?»
      Match a single character that is a “digit” «\d»
      Match a single character that is a “whitespace character” «\s{1}»
         Exactly once «{1}»
      Match a single character that is a “digit” «\d?»
         Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Assert position at the end of a line «$»