[php] 지정된 위치에 문자열 삽입

그렇게 할 수있는 PHP 함수가 있습니까?

strpos하위 문자열의 위치를 ​​얻는 데 사용 하고 있으며 string그 위치 뒤에 를 삽입하고 싶습니다 .



답변

$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);

http://php.net/substr_replace


답변

$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);

substr PHP 매뉴얼


답변

시도해보십시오. 하위 문자열 수에 관계없이 작동합니다.

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

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

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

    // bca+++def a+++bcdef
?>


답변

putinplace 함수 대신 stringInsert 함수를 사용하십시오. 나중에 함수를 사용하여 mysql 쿼리를 구문 분석했습니다. 출력은 괜찮아 보이지만 쿼리 결과 오류를 추적하는 데 시간이 걸렸습니다. 다음은 하나의 매개 변수 만 필요한 stringInsert 함수 버전입니다.

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  


답변

str_replace($sub_str, $insert_str.$sub_str, $org_str);


답변

나는 그것을 위해 내 오래된 기능 중 하나를 가지고있다 :

function putinplace($string=NULL, $put=NULL, $position=false)
{
    $d1=$d2=$i=false;
    $d=array(strlen($string), strlen($put));
    if($position > $d[0]) $position=$d[0];
    for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
    for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
    return $string;
}

// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) ); //RESULT: My dog don't love postman

이것은 완벽하게 작동하는 작고 강력한 기능입니다.


답변

이것은 키워드를 찾은 후 다음 줄에 텍스트를 추가하는 간단한 해결책이었습니다.

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

산출:

This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.