我想删除只包含一个数字、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
问题是只有最后一行会发生变化,它有一个或两个数字。
我能做什么?
你可以试试这个正则表达式:
(?:^|'n)'d?'s?'d?(?='n|$)
正则表达式住在这里。
(?:^|'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
希望对您有所帮助。
如果您有
多行文本,请使用
^'d(?:'h?'d)?$'n?
正则表达式细分:
-
^
- 行首 -
'd
- 一位数 -
(?:'h?'d)?
- 一个可选的(1 或 0 次(序列,由 1 或 0 个水平空格 ('h?
( 和一个数字 ('d
(
组成 -
$
- 行尾 -
'n?
- 可选换行符。
查看正则表达式演示
$re = '/^'d(?:'h?'d)?$'n?/m';
$str = "text 1'n1 text'n11'n1 0'n111'n1";
echo $result = preg_replace($re, "", $str);
查看 IDEONE 演示
<?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 «$»