Wednesday, 15 July 2015

php - Appending html Tag with regex -



php - Appending html Tag with regex -

i alter string from:

<a href....>*</a>

to:

<article><a href=....>*</a></article>

i have tried understanding of regex bad.

$n = '/<a (.*)[^>]>/'; $h = '/<article><a(.*)[^>]>/i','/<\/a></articla>/'; $reg = preg_replace($n, $h, $content);

your solution match <a href...> not closing element.

try this:

$n = '/(<a [^>]*>([^<]*<(\/[^a])|[^\/])*\/a>)/i'; $h = '<article>${1}</article>'; $reg = preg_replace($n, $h, $content);

edit:

now respects kid elements

explenation:

<a [^>]*>

matches start tag.

( [^<]*<

finds next tag.

(\/[^a])|[^\/] )*

ensures, next tag not closing </a> , matches every other tag.

\/a>

matches closing </a>, finally. (note: < has been matched).

php regex

No comments:

Post a Comment