preg_match -ing from lines in a .txt file (with spaces and brackets!)

雨燕双飞 提交于 2019-12-02 04:47:49

Replace the fourth line in the code you supplied with

$manualRemovePattern = "/(?:" . implode("|", array_map(function($i) {
    return preg_quote(trim($i), "/");
}, explode(PHP_EOL, $file))) . ')/';

The main idea is:

  • Split the file contents you obtained into lines with explode(PHP_EOL, $file)
  • Then you need to iterate over the array and modify each item in the array (which can be done with array_map)
  • Modifying the array items involves adding escaping \ before any special regex metacharacter and a regex delimiter chosen by you (in this case, /), and this is done with preg_quote(trim($i), "/")
  • Note I remove any leading/trailing spaces with trim from the array items - just in case.

To match them as whole words, use word boundaries:

$manualRemovePattern = '/\b(?:' . implode('|', array_map(function($i) {
    return preg_quote(trim($i), '/');
}, explode(PHP_EOL, $file))) . ')\b/';

To match them as whole strings, use ^/$ anchors:

$manualRemovePattern = '/^(?:' . implode('|', array_map(function($i) {
    return preg_quote(trim($i), '/');
}, explode(PHP_EOL, $file))) . ')$/';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!