Forum Moderators: coopster

Message Too Old, No Replies

REGEX: chain substitution

         

carlos1234

4:27 pm on Dec 11, 2014 (gmt 0)

10+ Year Member



Hi everybody,

I fill a variable with html, once has been charged I need to add a "<br />" at the begining and at the ending of each link found in the variable. As an example "<a ......>.....</a>" to "<br /><a ......>.....</a><br />"

I use the regex expression "%(<a.*?>)%is" to find the initial link tag but I don't know how to tell the preg_replace to do the substitution with "<br /><a.*?>". The link closing tag is easier to do so....:).

Thanks.

PD: I don't know what I'm puting into the variable, that's why I have to do it afterwoods, once the variable is charged. Is like to be reading a text with html without knowing its content.

lucy24

6:10 pm on Dec 11, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I need to add a "<br />" at the begining and at the ending of each link

Approaching it purely in RegEx terms, without reference to php:

pattern:
(<a[^>]+>[^<>]+</a>)


substitution:
<br>$1<br>

(Or, if you insist,
<br/>
)

Here it's much easier to treat the whole address as a package. Can we safely assume there will be no html markup within the anchor text? Otherwise the pattern becomes a good bit more complicated.

But what if your text says something like
check out this terrific site at example.com/pagename.

i.e.
check out this terrific site at <a href = "http://www.example.com/pagename">pagename</a>.

Applying the replacement would leave the final punctuation stranded on a new line, even if it happened to be the end of a paragraph. Is this OK?

Will your text ever contain other kinds of anchors, like
<a name = "something" id = "something">

? Those would need to be excluded, again making for a more complicated pattern, but still perfectly doable.

penders

12:49 am on Dec 12, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Do you need to use a regex...?

$result = str_ireplace(array('<a','a>'), array('<br><a','a><br>'), $source);

lucy24

6:47 am on Dec 12, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Spoilsport :P

penders

2:51 pm on Dec 12, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



lol (Still a very informative regex post I might add! :)