Reputation: 1
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?
Upvotes: 0
Views: 51
Reputation: 4484
From his comments, it now appears that the OP targets a more general use, adding \t
s 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]
. "\n" . preg_replace('/([^\n]+)/', "\t$1", $matches[2])
. "\n" . $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.
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\n\t$2</a>', $text);
Here is it working: https://regex101.com/r/qo2N22/1.
Upvotes: 1