【问题标题】:regex/php code for replace text between two tags用于替换两个标签之间的文本的正则表达式/php代码
【发布时间】:2014-01-12 20:18:33
【问题描述】:

我声明我不是正则表达式专家,但我正在尝试根据此处找到的一些示例创建代码。我的需要是用 WordPress 表中的字符串 <li class="ingredient"> 替换字符串 <li>。但是,必须仅对 [ingredients title = XXXX][/ingredient] 之间的文本进行此更改。

我编写了这段 PHP 代码,它可以工作,但它删除了替换 [ingredients[/ ingredients]

因为正如我所说,他们不是该领域的专家,任何人都可以帮助我更改代码以做我需要的事情吗?

这是我的 PHP 脚本:

<?php
$connection = mysql_connect("mysql.xxxxxxxxx","xxxxx","xxxxxxxx");
$db =  mysql_select_db ("xxxxxxx");

$sql = "SELECT ID,post_content FROM wp_7pchjn_posts";    

$result = mysql_query($sql);    

while ($row = mysql_fetch_assoc($result))
    {
    $id = $row['ID'];
    $search= $row['post_content'];

    if (strpos($search,'[ingredients') !== false) {

        $text = preg_replace_callback("/\[ingredients(.*?)\[\/ingredients\]/ism", function($match) {
          return str_replace("<li>", "<li class=\"ingredient\">", $match[1]);
        }, $search);

        $sql = "UPDATE yourtable set post_content='".$text."' where id='".$id."'";
        mysql_query($sql);
    }
}

mysql_close(); 

?>

【问题讨论】:

    标签: php html regex wordpress replace


    【解决方案1】:

    您需要更改捕获的组:

    (\[ingredients.*?\[\/ingredients\])/ism
    

    PHP 代码:

    $text = preg_replace_callback("/(\[ingredients.*?\[\/ingredients\])/ism", function($match) {
              return str_replace("<li>", "<li class=\"ingredient\">", $match[1]);
            }, $search);
    

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多