在指定位置插入字符串

Ale*_*lex 251 php string

是否有PHP功能可以做到这一点?

我正在使用strpos获取子字符串的位置,我想string在该位置之后插入一个.

urm*_*aul 522

$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
Run Code Online (Sandbox Code Playgroud)

http://php.net/substr_replace

  • 这应该是公认的答案.内置函数任何时候都优先于用户创建的函数. (24认同)
  • 是的,第四个参数为"0"会导致插入重播字符串而不覆盖任何原始字符串. (13认同)
  • 很棒的答案.但对于懒惰的人(像我一样),你的帖子中应该有一个简短的解释.我现在就做,并从php.net复制'n'paste:"当然,如果长度为零,那么这个函数将具有在给定的起始偏移处将替换插入字符串的效果." (6认同)
  • 注意:函数substr_replace()不是多字节安全的!你的$ pos可能会出现在UTF-8角色的中间.您可能需要使用@ tim-cooper的解决方案,但使用mb_substr(). (6认同)

Tim*_*per 72

$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
Run Code Online (Sandbox Code Playgroud)

substr 在PHP手册上


ale*_*ets 10

尝试一下,它适用于任意数量的子串

<?php
    $string = 'bcadef abcdef';
    $substr = 'a';
    $attachment = '+++';

    //$position = strpos($string, 'a');

    $newstring = str_replace($substr, $substr.$attachment, $string);

    // bca+++def a+++bcdef
?>
Run Code Online (Sandbox Code Playgroud)


小智 7

使用stringInsert函数而不是putinplace函数.我使用后来的函数来解析mysql查询.虽然输出看起来不错,但是查询导致了一个错误,我花了一些时间来追踪.以下是我的stringInsert函数版本,只需要一个参数.

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我的简单解决方案,也就是在找到关键字后将文本附加到下一行。

$oldstring = "This is a test\n#FINDME#\nOther text and data.";

function insert ($string, $keyword, $body) {
   return substr_replace($string, PHP_EOL . $body, strpos($string, $keyword) + strlen($keyword), 0);
}

echo insert($oldstring, "#FINDME#", "Insert this awesome string below findme!!!");
Run Code Online (Sandbox Code Playgroud)

输出:

This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.
Run Code Online (Sandbox Code Playgroud)