<?php
$tests = array(
'<a href="mailto:Bob@Bob.com">E-mail</a> Bob.',
'<a href="mailto:Bob@Bob.com">Bob</a>',
'Bob',
'<a href="mailto:Sue@Sue.com">Sue</a>',
);
### For each test...
foreach ($tests as $test) {
echo '<hr /><b>Analyzing: ', htmlentities($test), '</b><br />';
### ...separate the tags from the text.
$pieces =
preg_split(
'/(<.+?>)/',
$test,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
### For each piece...
foreach ($pieces as &$piece) {
### ...make the substitution on the non-tag pieces.
if (strpos($piece, '<') === FALSE) {
echo $piece, '<br>';
$piece = str_replace('Bob', 'Bill', $piece);
}
### ...and ignore the tag pieces.
else {
echo 'Skipping ', htmlentities($piece), '<br>';
}
}
### Now put them back together...
$string = implode('', $pieces);
echo '<b>Final: ', htmlentities($string), '</b><br>';
}
?>