来自文字:
Text...
Target row
Text...
我需要删除行,字符串'目标行'和下一个空行。所以我需要得到:
Text...
Text...
答案 0 :(得分:2)
$result = preg_replace('/^Target row\r?\n\r?\n/m', '', $subject);
如果空行必须真的不包含任何内容,甚至不包含空格/制表符。如果允许使用空格/制表符,请使用
$result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject);
答案 1 :(得分:0)
你很少有“大选择”。
$req = ''; // Partial string to get matched
$length = 0; // If you had a full string not partial, use strlen here
// Now find beginning, don't forget to check with === false
$pos = strpos( $text, $req);
$end = strpos( $text, "\n", $pos+1);
// If you don't have criteria that match from start
$start = strrpos( $text, "\n", $pos-1);
// And build resulting string (indexes +/-2, do your job):
$result = substr( $text, 0, $start-1) . substr( $text, $end+2);
preg_match_all()
如果你需要匹配更复杂的模式,你可以使用preg_match_all()
和标记PREG_OFFSET_CAPTURE
(以获得起始偏移),而不是使用与前面示例相同的算法(之前应该更有效)。
preg_replace
正如Tim Pietzcker建议的那样,但这个解决方案并不关心自由行中的空格
$result = preg_replace('/^Target row\r?\n\s*\r?\n/m', '', $subject);
explode
和next
$array = explode( "\n", $text);
// I would use this only when loading file with:
$array = file( 'file.txt');
while( $row = next( $array)){
if( matches( $row)){ // Apply whatever condition you need
$key1 = key( $array);
next( $array); // Make sure it's not === false
$key2 = key( $array);
unset( $array[$key1]);
unset( $array[$key2]);
break;
}
}
fgets
$fp = fopen( 'file.txt', 'r') or die( 'Cannot open');
while( $row = fgets( $fp)){
if( matched( $row)){
fgets( $fp);// Just skip line
} else {
// Store row
}
}