Forum Moderators: coopster
Example:
base string:
"<h2>This is a title</h2>"
string to be inserted:
"<a href="#top"></a>"
preg_replace will change base string to :
"<h2>This is a title<a href="#top"></a></h2>"
Can someone help?
Begin by making a match on the existing pattern:
if (preg_match('/<h\d[^>]*>[^<]+<\/h\d>/i',$string)) {
.....
translation:
<h\d[^>]*?> = begins with literal <h followed by a single digit followed by zero or more (*) of anything not a >. This is to include any other attributes you might have, e.g. <h1 class="main-head">. The ? is a quantifier, limiting the search to the first instance found so that zero more of "any character not a >" doesn't slurp up the whole string. Subpattern ends with >.
[^<]+ = followed by one or more of anything not a <. This one becomes important in the next step.
<\/h\d> = closing tag, e.g. </h1>
i = case insensitive, just in case. <H1> We'll add the global modifer in the replace; this means to apply changes globally to a large block of text.
Once you get that working, you can "save" subpatterns in parentheses. They read from left to right ()()() and are stored in temporary numbered variables $1, $2, $3, consecutively.
So using the working match, you store the strings and add your anchor.
$anchor = '<a href="#top"></a>';
if (preg_match('/<h\d[^>]*>[^<]+<\/h\d>/i',$string)) {
$string = preg_replace('/(<h\d[^>]*>)([^<]+)(<\/h\d>)/ig',"$1$2$anchor$3",$string);
}
(As said, typed out on the fly, may contain errors or require tweaking.)
[edited by: eelixduppy at 6:21 pm (utc) on Sep. 23, 2009]
[edit reason] disabled smileys [/edit]