regex - 用正则表达式替换结尾随机并添加字符
问题描述
我有一个带有随机结尾字符串的 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
解决方案
您可以在一组中捕获要匹配和删除的模式之前的内容。然后在替换中使用第一个捕获组:
^(.*)-[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
例如
$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
推荐阅读
- height - 如何获取 Kurento 复合混音器(gstreamer)的视频源大小?
- google-sheets - 将键值对映射到 Google Sheets API v4 (PHP) 中的特定列?
- r - 在 R 中创建子集
- reactjs - 根据另一个状态反应状态(表单输入验证)
- ssh - 尝试在气流中创建和运行 ssh 时,收到此错误“SSH 操作员错误:没有可用的身份验证方法”
- opengl - 如果我使用 Glad 而不是 GLEW,我会错过什么吗?
- python - 如何杀死由 python ctypes.LoadLibrary 创建的 C pthreads
- python - 通过 websocket 发送的文件在接收时变得太大
- react-native - _reactNative.UIManager.setLayoutAnimationEnabledExperimental 不是函数
- .net - 当前上下文中不存在“QueryHelpers”-.NET 3.1