Replace i and b tags with em and strong tags using PHP

Here's a function that replaces <i> and <b> with <em> and <strong>. This comes in very handy in migrations. In the future, it would be nice to also convert <font> tags.

<?php
/**
  * Replaces <i> and <b> tags with <em> and <strong> tags.
  * 
  * @param string $string The input string.
  * @return string The filtered text.
  */
function replaceTagsIB($string) {
  $pattern = array('`(<b)([^\w])`i', '`(<i)([^\w])`i');
  $replacement = array("<strong$2", "<em$2");
  $subject = str_replace(array('</b>', '</i>', '</B>', '</I>'), array('</strong>', '</em>', '</strong>', '</em>'), $string);
  return preg_replace($pattern, $replacement, $subject);
}
 
?>

And here's a little test to show it in action:

<?php
 
$string = <<< HERE
<i>iiiii</i>
<b>bbbbb</b>
<I>IIIII</I>
<B>BBBBB</B>
<i attribute="value">iiiii</i>
<b attribute="value">bbbbb</b>
HERE;
 
$result = <<< HERE
<em>iiiii</em>
<strong>bbbbb</strong>
<em>IIIII</em>
<strong>BBBBB</strong>
<em attribute="value">iiiii</em>
<strong attribute="value">bbbbb</strong>
HERE;
 
print replaceTagsIB($string) === $result ? 'Success' : 'Failure';
?>

Tags

Article Type

General