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/iso's etc). It has other ways of filtering too but I've just highlighted the section I'm trying to add. I want a external .txt file I can put names of files in like so (separated by a single line break):
Pacman 2 (USA)
Space Invaders (USA)
Asteroids (USA)
Something Else (Europe)
And then running the script will search the directory and place any matching filenames in the "removed" folder. It loops fine with all the other filtering techniques it uses. I'm just trying to add my own (unsuccessfully!)
$gameList = trim(shell_exec("ls -1"));
$gameArray = explode("\n", $gameList);
$file = file_get_contents('manualremove.txt');
$manualRemovePattern = '/(' . str_replace(PHP_EOL, "|", $file) . ')/';
shell_exec('mkdir -p Removed');
foreach($gameArray as $thisGame) {
if(!$thisGame) continue;
// Probably already been removed
if(!file_exists($thisGame)) continue;
if(preg_match ($manualRemovePattern , $thisGame)) {
echo "{$thisGame} is on the manual remove list. Moving to Removed folder.\n";
shell_exec("mv \"{$thisGame}\" Removed/");
continue;
So this is working when I put names of games with no spaces or brackets in the .txt file. But spaces or brackets (or both) are breaking it's functionality. Could someone help me out?
Many thanks!
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 withpreg_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))) . ')$/';
来源:https://stackoverflow.com/questions/50963005/preg-match-ing-from-lines-in-a-txt-file-with-spaces-and-brackets