programing

지정된 위치에 문자열 삽입

javaba 2022. 12. 25. 09:46
반응형

지정된 위치에 문자열 삽입

그것을 할 수 있는 PHP 함수가 있나요?

사용하고 있다strpos서브스트링의 위치를 얻으려면 , 그리고 나는 a를 삽입하고 싶다.string그 포지션 다음에.

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

http://php.net/substr_replace

위의 토막에서$pos에서 사용됩니다.offset함수의 인수입니다.

오프셋
오프셋이 음이 아닌 경우 오프셋의 문자열로 대체가 시작됩니다.

오프셋이 음수인 경우 문자열 끝에서 오프셋의 두 번째 문자부터 치환이 시작됩니다.

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

substrPHP 매뉴얼에서

시험해 보세요.여러 개의 서브스트링에서 동작합니다.

<?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 쿼리를 해석하기 위해 후술 함수를 사용하고 있었습니다.출력은 정상이었지만 쿼리 결과 오류가 발생하여 추적에 시간이 걸렸습니다.파라미터가1개만 필요한 stringInsert 함수의 버전을 다음에 나타냅니다.

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

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

$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.
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

이것은 그 일을 완벽하게 수행하는 작고 강력한 기능이다.

덧붙이고 싶은 것이 있습니다.저는 tim coper의 답변이 매우 유용하다는 것을 알았습니다.저는 이 답변을 사용하여 일련의 위치를 받아들여 모든 위치에 삽입하는 방법을 만들었습니다.그것은 다음과 같습니다.

EDIT: 이전 기능을 가정한 것 같습니다.$insertstr배열이 정렬된 것은 1글자뿐입니다.이것은 임의의 문자 길이로 동작합니다.

function stringInsert($str, $pos, $insertstr) {
    if (!is_array($pos)) {
        $pos = array($pos);
    } else {
        asort($pos);
    }
    $insertionLength = strlen($insertstr);
    $offset = 0;
    foreach ($pos as $p) {
        $str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
        $offset += $insertionLength;
    }
    return $str;
}

단순하고 다른 해결 방법:

function stringInsert($str,$insertstr,$pos)
{
  $count_str=strlen($str);
  for($i=0;$i<$pos;$i++)
    {
    $new_str .= $str[$i];
    }

    $new_str .="$insertstr";

   for($i=$pos;$i<$count_str;$i++)
    {
    $new_str .= $str[$i];
    }

  return $new_str;

}  
function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}

이상한 대답이야!sprintf [link to documentation]를 사용하면 다른 문자열에 문자열을 쉽게 삽입할 수 있습니다.이 기능은 매우 강력하며 여러 요소 및 기타 데이터 유형도 처리할 수 있습니다.

$color = 'green';
sprintf('I like %s apples.', $color);

실마리를 주다

I like green apples.

언급URL : https://stackoverflow.com/questions/8251426/insert-string-at-specified-position

반응형