doupai8533 2016-10-09 21:34
浏览 26

添加选项卡以使用正则表达式锚定文本

I have something like this ;

<a href="#" class="example">
Link 1
</a>
<a href="#" class="example">
Link 2
</a>
<a href="#" class="example">
Link 3
</a>

I want add tab before anchor text. Like this;

<a href="#" class="example">
  Link 1
</a>
<a href="#" class="example">
  Link 2
</a>
<a href="#" class="example">
  Link 3
</a>

How can I do this with regex?

</div>
  • 写回答

1条回答 默认 最新

  • dongyou2279 2016-10-09 23:32
    关注

    Edit, following the question extension

    From his comments, it now appears that the OP targets a more general use, adding \ts to indent all lines between the opening and closing tag.
    Then its time to remember that regex is not a good way to parse HTML, as frequently observed here.

    But in this yet not too wide context we can propose a solution.
    Unless somebody finds a better solution, I don't see a way to do it without 2 nested steps:

    $updated_text = preg_replace_callback(
        '/(<a[^>]*>)\s*(.*?)\s*(<\/a>)/s',
        function($matches) {
            return $matches[1]
              . "
    " . preg_replace('/([^
    ]+)/', "\t$1", $matches[2])
              . "
    " . $matches[3];
        },
        $text
    );
    

    Note that, in addition to be a poor way of doing it, it's much time consuming due to the .*? (not greedy) quantifier.


    Initial answer

    Thanks to the @bobblebubble suggestion I just understood what means "I want add tab" (I previously thought only to browser's tabs :).

    But I find its solution a bit too general: it'll add tab to any line which is not a tag!
    I'd prefer to closely look for only <a> tags, and only when presented like in the OP's example:

    $updated_text = preg_replace('/(<a[^>]*>)\s*([^<]*)\s*<\/a>/', '$1
    \t$2</a>', $text);
    

    Here is it working: https://regex101.com/r/qo2N22/1.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥70 2048小游戏毕设项目