在每个开始标记后插入

时间:2010-08-12 03:35:39

标签: php

如何在包含HTML的字符串中的每个开始标记之后使用preg_replace插入给定字符串?例如,如果我有字符串:

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

我要插入<b>,结果应为:

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

1 个答案:

答案 0 :(得分:3)

我冒昧地为你添加了结束标签。如果这确实不是所需的行为,那么只需发送每个数组的第一个成员而不是数组本身。

$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);