如何在旧字符串中的所有关键字的4个字符之前添加新字符串

时间:2014-12-20 05:32:16

标签: php string add

示例:

$oldstring = "How to Formatqw101-put returns between paragraphsre51-for linebreak add 2 spaces at endfd54-italic_ or **bold**se65-indent code by 4 spaces";
$newstring = "<br/>";

我想在“ - ”的前4个字符中添加$ newstring,所以当成功看起来像这样

How to Format<br/>qw101-put returns between paragraphs<br/>re51-for linebreak add 2 spaces at end<br/>fd54-italic_ or **bold**<br/>se65-indent code by 4 spaces

1 个答案:

答案 0 :(得分:0)

试试这个:

$oldstring = "How to Formatqw101-put returns between paragraphsre51-for linebreak add 2 spaces at endfd54-italic_ or **bold**se65-indent code by 4 spaces";
$arr = explode(' ', $oldstring);
$res = array();
foreach($arr as $item) {
    if(strpos($item, '-') !== false) {
        $pos = strpos($item, '-');
        $item = substr_replace($item, '<br/>', $pos-4, 0);
    }
    $res[] = $item.' ';
}
echo implode('', $res);