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

后端 未结 1 1951
离开以前
离开以前 2021-01-27 00:29

So I have got this far on my own but It looks like I have found the limit of my PHP knowledge (which isn\'t very much at all!). This script is for filtering filenames (game roms

1条回答
  •  我在风中等你
    2021-01-27 01:04

    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))) . ')$/';
    

    0 讨论(0)
提交回复
热议问题