开发者

Insert after each opening tag

How do I use preg_replace to insert a given string after each opening tag in a string containing HTML? For example, if I have the string:

$str = 'sds<some_tag>ttt</some_tag>dfg<some_tag>vvv</some_tag>sdf';

and I want to insert <b>, the result should be:

$str = 'sds<some_tag><b>ttt</some_tag>dfg<some_tag><b>vvv</some_tag>sdf';开发者_运维技巧


I took the liberty of adding closing tags for you. If this is really not the desired behavior, then just send in the first member of each array instead of the array itself.

$str = 'sss<some_tag with="attributes">ttt</some_tag>dfg';
$str .= '<some_tag with="other[] attributes" and="still-more-attributes">';
$str .= 'vvv</some_tag>sdf';


function embolden($string, $some_tag)
{
    //make our patterns
    $patterns = array();
    $patterns[] = '/<'.$some_tag.'(.*)>/U';
    $patterns[] = '/<\/'.$some_tag.'(.*)>/U';

    // without the non-greedy `U` modifier, we'll clobber most of the string. 
    // We also use capturing groups to allow for replacing any attributes that
    // might otherwise get left behind. We can use multiple capturing groups in 
    // a regular expression and refer to them in the replacement strings as $n
    // with n starting at 1

    //make our replacements
    $replacements = array();
    $replacements[] = '<'.$some_tag.'$1><b>';
    $replacements[] = '</b></'.$some_tag.'$1>';

    return preg_replace($patterns, $replacements, $string);
}

//htmlentities for convienent browser viewing
$output = embolden($str, 'some_tag');
echo htmlentities($str);
echo '<br>';
echo htmlentities($output);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜