php - 如何使用正则表达式替换内容

标签 php mysql regex wordpress

我的数据库有问题。我正在使用的网站使用的是一个旧的 cms,它有一个非常奇怪的数据库结构,链接不正常,但有一些自定义的短代码版本。现在,当网站迁移到 wordpress 时,这些链接被一些脚本所取代。但是它跳过了数据库中大约 2k 篇文章(我们有大约 27k 篇文章)。我能够找到的是这些是我的问题的可能组合。

<a href="{{article::4111}}">Article title</a>
<a href="{{article::4111}}">{{article:4111}}</a>
or just {{article::4111}}

这是一篇文章的例子:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
faucibus vehicula mauris. Quisque sed ex ac lacus tempus blandit. 
Fusce in leo sit <a alt="Some text" title="other text" href="{{article::4111}}">{{article::4111}}</a> nisi porttitor volutpat ac vel tellus. Donec in 
pellentesque nunc. Maecenas congue libero dui, id fermentum ligula 
consequat ac. Suspendisse tempus magna lorem, nec facilisis dolor 
sodales at. Donec laoreet at justo non {{article::4511}}. Lorem ipsum dolor 
sit amet, consectetur adipiscing elit. Aliquam porttitor, orci nec 
molestie interdum, libero est molestie sapien, efficitur facilisis mi 
diam non enim. Etiam viverra dolor ut augue vestibulum, placerat 
condimentum magna tincidunt. Integer rhoncus nulla at elit sodales 
pharetra. Maecenas congue erat ut tellus imperdiet molestie. Sed sed 
metus tincidunt, finibus ante quis, consequat orci. Nam non massa nec 
ipsum congue pretium. Curabitur sollicitudin, dui vitae venenatis 
hendrerit, tortor massa mattis nisl, vel rutrum enim nibh in tortor.
Related news:
{{article::75145}}

我在想的是使用 php 和正则表达式来找到它并用普通链接替换它,但我的问题是我不太了解正则表达式,我需要进行某种检查以查看哪些可能的情况是。因此,如果有人遇到过这样的问题,我将非常感谢您的帮助。但主要的问题是,它可以在文章的任何部分找到,并且出现的次数是随机的(可以只有一次,也可以是十次或二十次),::之后的部分是文章的 ID,是随机的,所以使用经典的爆炸功能是行不通的。到目前为止我所做的是导出我的 wp_posts 表并导入到自定义数据库中,并有一个干净的 php 项目只连接到该表,我将使用纯 PHP 而不是 wp 函数。那么,如果它仅位于 href="" 内,我需要做什么仅标记我需要用完整链接替换它,但如果它位于 <a> </a> 之间和一个 href=""标签 我需要用链接替换 ​​href 标签,将第二部分替换为标题。很抱歉描述这么长,但我认为这将有助于最好地描述我的问题。

最佳答案

要匹配它们非常简单:/{{article::\d+}}/ 这匹配 article:: 后跟一个或多个数字。 Demo .

要替换给定字符串中的所有这些,请使用如下内容:

<?php
$str = '<a href="{{article::4111}}">Article title</a>
<a href="{{article::4111}}">{{article::4111}}</a>
or just {{article::4111}}
';

$str = preg_replace_callback(
   '/{{article::(\d+)}}/',
   function($match){
      // some callback function, where $match[1] contains the number
      // here we just add a path with the number as argument for a file article.php
      return 'http://domain.com/article.php?id='.$match[1];
   },
   $str
);

echo $str;
?>

在该函数中,您还可以进行一些数据库调用或其他任何操作来获取新的 URL。

关于php - 如何使用正则表达式替换内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466106/

相关文章:

php - 如何将连接的 MYSQL 字符串查询存储到 PHP 变量中?

php - mysql表结构问题(用户登录和用户登录fb)

php - 如何在PHP中记录调用当前函数的文件/行的名称?

php/超时/连接到服务器重置?

java - 我的登录身份验证 Servlet 出错

regex - 在 Vim 中,如何匹配 "="而不是 "=="?

regex - 用于Google Analytics(分析)的RegEx,可在网址中选择文本

JavaScript RegExp 排除特定文件扩展名和index.js

php - 在没有路由的情况下执行 Yii 模块

php - MySQL 选择上个月的行,但它包含(31/30/28 天)或闰年