dongweng9474 2016-10-19 13:52
浏览 32
已采纳

搜索页面并替换一些元素

I have 2 sets of tags on page, first is

{tip}tooltip text{/tip}

and second is

{tip class="someClass"}tooltip text{/tip}

I need to replace those with

<span class=„sstooltip”><i>?</i><em>tooltip text</em></span>

I dont know how to deal with adding new class to the <span> tag. (The tooltip class is always present)

This is my regex /\{tip.*?(?:class="([a-z]+)")?\}(.*?)\{\/tip\}/.

I guess I need to check array indexes for class value, but those are different, depending on {tip} tag version. Do I need two regular expressions, one for each version, or there is some way to extract and replace class value?

php code:

$regex = "/\{tip.*?(?:class=\"([a-z]+)\")?\}(.*?)\{\/tip\}/";
$matches = null;
preg_match_all($regex, $article->text, $matches);

if (is_array($matches)) {
    foreach ($matches as $match) {
        $article->text = preg_replace(
            $regex,
            "<span class=tooltip \$1"."><i>?</i><em>"."\$2"."</em></span>",
            $article->text
        );
    }
}
  • 写回答

1条回答 默认 最新

  • dongxie8856 2016-10-19 14:11
    关注

    Here's your answer (I've also made it a bit more robust):

    {tip(?:\s+class\s*=\s*"([a-zA-Z\s]+)")?}([^{]*){\/tip}
    

    PCRE (which PHP uses, if memory serves) will automatically pick up that the first capture group (which grabs the classes) is empty in the first case, and just substitute the empty string in the replacement. The second case is self-explanatory.

    Your replacement code, then, will look like this:

    $article->text = preg_replace(
        '/{tip(?:\s+class\s*=\s*"([a-zA-Z\s]+)")?}([^}]*){\/tip}/',
        '<span class="tooltip $1"><i>?</i><em>$2</em></span>',
        $article->text
    );
    

    Yout don't need to check if the regex matches beforehand - that's implied by preg_replace, which is performing a regex match and then replacing any text matched by the pattern with that text. If there are no matches, no replacement occurs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口