regex - php or sed: insert html tag within existing html tag when a string is matched -


how can search word "box" within html code below:

<p>text here ok</p> <h4> box 1.2</h4> <p>text here ok</p> 

and have output follows?

<p>text here ok</p> <h4><a name="box1.2"></a>box 1.2</h4> <p>text here ok</p> 

note line break between <h4> , box needs removed. other thing have "box 2.0", "box 2.3", etc. word "box" has matching pattern.

using php:

$str = '<p>text here ok</p> <h4> box 1.2</h4> <p>text here ok</p>';  $new = preg_replace('/\s*(box)\s*(\d+(:?\.\d+)?)/i', '<a name="$1$2">$1 $2</a>', $str); echo $new; 

explanation:

/ #start delimiter     \s* #match spaces/newlines (optional/several)     (box) #match "box" , group (this used $1)     \s* #match spaces/newlines (optional/several)     (\d+(:?\.\d+)?) #match number (decimal part optional) , group (this used $2) / #end delimiter #regex modifier: => case insensitive 

Comments