通过移动特定单词的位置来使用 PHP 清理数据


Clean up data with PHP by moving position of specific words

我有一些数据想要清理。这应该是一个常见问题,但我还没有找到解决方案。数据如下所示,应转换为:

  • 最简单,最简单>
  • 夜,黑的 ->黑
  • 行程,A - 向西走 -> 一次旅行 - 向西走
  • 路易斯安那州缪斯:3个香颂 -> 缪斯:3个香颂
  • 激情,La (OMG
  • ) -> La Passion (OMG)
  • 约翰尼 - 一个去,>一个去,约翰尼 - 一个去
  • 和平,"伟大的人"->和平"伟大的人"

特殊情况是双重发生:

  • 互联网一代,梦想,>互联网一代 - 梦想

保持原样,因为没有"停止"字符,并且单词"the"不在末尾:

  • 查克,战士 ->查克,战士

因此,有多个单词需要移动到开头(the,a,la)和几个"停止"字符[:,-,(,",字符串的结尾]。逗号前可以有空格,也可以不逗号。

我试图用preg_replace解决问题,但无法提出可行的解决方案。我相信对于更有经验的人来说是可能的。非常感谢您对此的帮助!

我根据elclanrs的答案使用的最终解决方案:

$tests = array(
    "Easiest, The",
    "Heaviest,The",
    "Night, The - Is black",
    "Trip,A - Go west",
    "Muse, La: 3 chansons",
    "Passion, La (OMG)",
    "Johnny - One to go for, The",
    "Peace, The '"Great one'"",
    "Chuck, the fighter",
    "Mason, the hero ",
    "Internet Generation, The - Dream, A",
);
$patt = '/([^,:"(-]+)'s*?,'s*?([^,:"(-]+)/';
foreach ($tests as $test) {
    if (preg_match('/(([:"(-]+)'s*?)|,'s*?'w+'s*?$/', $test)) {
        echo trim(preg_replace('/'s+:/', ':', preg_replace('/'s+/', ' ', preg_replace($patt, '$2 $1 ', $test)))) . PHP_EOL;
    } else {
        echo "Not modified: " . $test . PHP_EOL;
    }
}

这将提供:

The Easiest
The Heaviest
The Night - Is black
A Trip - Go west
La Muse: 3 chansons
La Passion (OMG)
Johnny - The One to go for
The Peace "Great one"
Not modified: Chuck, the fighter
Not modified: Mason, the hero 
The Internet Generation - A Dream

所以我只是跳过不需要修改的字符串并删除所有不必要的空格。

这是一个可能的解决方案:

$tests = array(
    "Easiest, The",
    "Night, The - Is black",
    "Trip,A - Go west",
    "Muse, La: 3 chansonss",
    "Passion, La (OMG)",
    "Johnny - One to go for, The",
    "Peace, The '"Great one'""
);
$patt = '/([^,:"(-]+)'s*?,'s*?([^,:"(-]+)/';
foreach ($tests as $test) {
    echo preg_replace($patt, '$2 $1 ', $test) .'<br>';
}

这将打印出:

The Easiest 
The Night - Is black
A Trip - Go west
La Muse : 3 chansonss
La Passion (OMG)
Johnny - The One to go for 
The Peace "Great one"

如果您有更多规则[^,:"(-],则必须更新令牌。它并不完美,因为您可以看到:之前有一个空格,但我会把它和特殊情况留给您......