php - 在偏移处添加字符串?

标签 php string

如果我有一个像“test”这样的字符串,那么我有偏移量为 0-3 的字符。我想在偏移量 6 处添加另一个字符串。是否有一个简单的 PHP 函数可以做到这一点?

我正在尝试这个,但出现错误:

PHP Fatal error: Cannot use assign-op operators with overloaded objects nor string offsets in ...

我知道我可以连接这些字符串,但我想根据斯坦福 CoreNLP 的输出构建一个句子,提供字符串偏移位置 http://nlp.stanford.edu/software/example.xml (更多信息请访问http://nlp.stanford.edu/software/corenlp.shtml)

$strings[0] = "test";
$strings[1] = "new";

foreach($strings as $string) {

for($i = 0 ; $i <= strlen($string); $i++) {
    print $string[$i];
    if (!isset($sentence)) {
        $sentence = $string[$i];
    }
    else {
        $sentence[strlen($sentence)] .= $string[$i];

    }
    }
}

print_r ($sentence);

PHP 文档位于 http://www.php.net/manual/en/language.types.string.php

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

最佳答案

将字符串转换为数组,如果偏移量大于字符串长度,则使用您选择的填充字符填充缺失的索引,否则只需将字符串插入到相应的数组索引位置并内爆字符串数组.

请看下面的函数:

function addStrAtOffset($origStr,$insertStr,$offset,$paddingCha=' ')
{
    $origStrArr = str_split($origStr,1);

    if ($offset >= count($origStrArr))
    {
        for ($i = count($origStrArr) ; $i <= $offset ; $i++)
        {
            if ($i == $offset) $origStrArr[] = $insertStr;
            else $origStrArr[] = $paddingCha;
        }
    }
    else
    {
        $origStrArr[$offset] = $insertStr.$origStrArr[$offset];
    }

    return implode($origStrArr);
}

echo addStrAtOffset('test','new',6);

关于php - 在偏移处添加字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24630705/

相关文章:

php - 用 Mockery 模拟 Laravel Model::increment()

python - 如何将字典/列表存储在数据库中?

java - 有没有办法 println 来枚举和列出字符串中的单词?

c# - 在 C# 中替换同时包含波斯语和英语字母的字符串

C - 大串中的最大串

php - 将字符串拆分为字母数组 - 双字符字母 PHP

php - 编辑表的特定字段

php - 允许的内存大小 134217728 字节已用尽

php - FTP 视频上传和缩略图旋转问题

c# - 不会将字符串转换为十进制 c#(输入字符串的格式不正确。)