douwen4125 2015-04-07 20:23
浏览 92

来自使用特定<tags>的CMS数据库导入的Preg_replace

I'm currently working on a website project I'm developping from start to scratch with a home-made content management system. The former website was running under SPIP (a french CMS) and I'm working to import the old content from the SPIP database on the new platform.

Things are running well, I'm getting all the articles, managed to code a new URL rewriting engine that keeps the old rewrited links as they were,..

The trouble I'm encountering is with the TEXT field of the articles that contains special tags. I did use str_replace to convert basic bbcode-like tags to html, but I'm encountering some troubles while trying to use preg_replace on more advanced tags.

Here is how the tag looks like. It's containted between plain text in a $texte var:

<doc30292|right>

As you see, the syntax looks like <docID|alignment> I need to replace all the tags that looks like this by display_doc($id,$alignment)

I do manage to get the ID or the alignment using preg_match but I do want to use preg_replace and I do not know how to do this. PCRE isn't part of my strenghts...

Any help ?

$texte=nl2br($texte);
$texte=preg_replace('#(<br */?>\s*)+#i', '<br /><br/>', $texte);
    // SPIP Intertitre
$texte=str_replace("{{{","<h2>",$texte);
$texte=str_replace("}}}","</h2>",$texte);
// SPIP Gras
$texte=str_replace("{{","<b>",$texte);
$texte=str_replace("}}","</b>",$texte);
// SPIP Italic
$texte=str_replace("{","<i>",$texte);
$texte=str_replace("}","</i>",$texte);
preg_match('/<doc(.*?)\|/', $texte, $match);
var_dump($match);
echo $match[1];
  • 写回答

1条回答 默认 最新

  • dpxkkhu1812 2015-04-07 20:32
    关注
    <?php
    
    $subject = '<doc30292|right>';
    $pattern = '/<([^|]+)\|([^>]+)>/';
    
    if (preg_match($pattern, $subject, $tokens)) {
      list($_, $id, $alignment) = $tokens;
      echo sprintf('display_doc(%s, %s)', $id, $alignment);
    }
    

    For this I get the output display_doc(doc30292, right).


    As for replacing multiple occurrences, as mentioned in your comment below, I would use the more convenient preg_replace_callback() function:

    <?php
    
    $subject = 'dumbo<doc4711|left>bla<doc30292|right>blub<doc666|center>lamda';
    $pattern = '/<([^|]+)\|([^>]+)>/';
    
    echo preg_replace_callback(
        $pattern, 
        function ($_) { return sprintf('display_doc(%s,%s)',$_[1],$_[2]); }, 
        $subject);
    

    This obviously returns: dumbodisplay_doc(doc4711,left)bladisplay_doc(doc30292,right)blubdisplay_doc(doc666,center)lamda

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向