首页 > 解决方案 > 用正则表达式替换结尾随机并添加字符

问题描述

我有一个带有随机结尾字符串的 url 列表,如下所示:

paris-chambre-double-classique-avec-option-petit-dejeuner-a-lhotel-trianon-rive-gauche-4-pour-2-personnes-8ae0676c-aba2-4cf2-9391-91096a247672

paris-chambre-double-standard-avec-petit-dejeuner-et-acces-spa-pour-2-personnes-a-lhotel-le-mareuil-4-f707b0fe-31cb-4507-b7b3-7b91695bff9c 

现在我过去几天一直在尝试找到一个正则表达式来将此行转换为:

/paris-chambre-double-classique-avec-option-petit-dejeuner-a-lhotel-trianon-rive-gauche-4-pour-2-personnes.html

/paris-chambre-double-standard-avec-petit-dejeuner-et-acces-spa-pour-2-personnes-a-lhotel-le-mareuil-4-f707b0fe-31cb-4507-b7b3-7b91695bff9c.html

问题是随机字符串:

3d0b087-5701-4199-9d9c-147cca687263
33d0b087-5701-4199-9d9c-147cca687263

我需要在没有最后一个的情况下删除这部分 - 并添加 .html: 在 url 之前添加一个斜杠,如下所示:

我不想要这个:

/paris-chambre-doubletriplequadruple-confort-avec-petit-dejeuner-a-lhotel-de-france-gare-de-lyon-pour-2-a-4-pers-.html

但是这个 :

/paris-chambre-doubletriplequadruple-confort-avec-petit-dejeuner-a-lhotel-de-france-gare-de-lyon-pour-2-a-4-pers.html

这是一个新的 Linux 服务器,运行 MySQL 5、PHP 7 和 Apache 2

标签: regex

解决方案


您可以在一组中捕获要匹配和删除的模式之前的内容。然后在替换中使用第一个捕获组:

^(.*)-[a-f0-9]+(?:-[a-f0-9]+){4,5}$

这将匹配:

  • ^字符串的开始
  • (.*)在匹配任何字符 0 次以上的组中捕获
  • -[a-f0-9]+匹配连字符后跟 1+ 次 0-9 或 af
  • (?:-[a-f0-9]+){4,5}重复 4-5 次匹配连字符,后跟 1+ 次 0-9 或 af
  • $字符串结束

替换为正斜杠并捕获组 1,然后.html

/$1.html

正则表达式演示| php演示

例如

$strings = [
    "paris-chambre-double-classique-avec-option-petit-dejeuner-a-lhotel-trianon-rive-gauche-4-pour-2-personnes-8ae0676c-aba2-4cf2-9391-91096a247672",
    "paris-chambre-double-standard-avec-petit-dejeuner-et-acces-spa-pour-2-personnes-a-lhotel-le-mareuil-4-f707b0fe-31cb-4507-b7b3-7b91695bff9c"
];

foreach ($strings as $string){
    echo preg_replace('/^(.*)-[a-f0-9]+(?:-[a-f0-9]+){4,5}$/', '/$1.html', $string) . PHP_EOL;
}

结果:

/paris-chambre-double-classique-avec-option-petit-dejeuner-a-lhotel-trianon-rive-gauche-4-pour-2-personnes.html
/paris-chambre-double-standard-avec-petit-dejeuner-et-acces-spa-pour-2-personnes-a-lhotel-le-mareuil-4.html

推荐阅读