删除行尾的数字和括号,并在行的开头填充占位符

时间:2014-11-16 13:19:57

标签: php regex

1)如何删除所有数字,括号和's。字串后面的字符串?

2)如果在行的前面有占位符--,则应生成完整的关键字(如果主要关键字具有分页数,则它将作为关键字本身添加;如果后面没有分页数那个,只是以下部分是相关的[即Word1和Word2])

3)long关键字可能有换行符。应删除此换行符(即示例中的最后一行)

Keyword 533 --534
Word1 519, 522
-- any 123
-- another 45, 33
Word2
-- any 23
-- another 5, 3
Key-word 832-- 833,
Keyword, with comma 48, 50 -- 51, 527
Keyword (anything)
Keyword s. remove that
Keyword with
linebreak 12, 344

结果应为

Keyword
Word1
any Word1
another Word1
any Word2
another Word2
Key-word
Keyword, with comma
Keyword
Keyword
Keyword with linebreak

我的尝试:

$myfile = fopen("file.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {

    $re = "/\\d+(\\s*,\\s*\\d+)*|\\bs\\..*$/im";
    $str = fgets($myfile);
    $subst = "";
    $result = preg_replace($re, $subst, $str);
    if (trim($result)) echo trim($result) . "<br>";
}
fclose($myfile);

这适用于数字,逗号和s. - 字符串。但我不知道如何使用--占位符和换行符来做这件事。

1 个答案:

答案 0 :(得分:-1)

试试这个:

$myfile = fopen("file.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
     $re = "/\\d+(\\s*,\\s*\\d+)*|\\bs\\..*$|[-,]+|\\(.*\\)/im";
     $str = fgets($myfile);
     $subst = "";

     $result = preg_replace($re, $subst, $str);
     if (trim($result)) echo trim($result) . "<br>";
}
fclose($myfile);

live demo