【问题标题】:php - add string at offset?php - 在偏移量处添加字符串?
【发布时间】:2014-07-08 11:31:05
【问题描述】:

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

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

PHP 致命错误:不能在 ... 中使用重载对象或字符串偏移的赋值操作运算符

我知道我可以连接这些字符串,但我想根据来自 Stanford 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

写入超出范围的偏移会用空格填充字符串。非整数类型转换为整数。非法偏移类型发出 E_NOTICE。负偏移量在写入时发出 E_NOTICE 但读取空字符串。仅使用分配字符串的第一个字符。分配空字符串会分配 NULL 字节。

【问题讨论】:

  • 您是否尝试将字符串视为字符数组?通过这种方式,您可以根据需要添加字符甚至连接字符串。
  • 谢谢,这就是我在示例代码中尝试做的事情。
  • 这个方法不对,如果你想把它当作一个数组,你首先需要创建一个带有 strlen($yourstring) 块的数组,这样每个块都包含你的字符串的一个字符。

标签: php string


【解决方案1】:

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

请看下面的函数:

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);

【讨论】:

    【解决方案2】:

    要解决您的问题,首先您使用str_split 将字符串转换为数组,然后当您完成数组后,您可以对这些字符串执行任何类型的操作。

    代码:

    $s1 = "test";
    $s2 = "new";
    //converting string into array
    $strings[0] = str_split($s1, 1);
    $strings[1] = str_split($s2, 1);
    //setting the first word of sentence
    $sentence = $strings[0];
    //insert every character in the sentence of "new" word
    for ($i=0; $i < count($strings[1]); $i++) { 
        $sentence[] = $strings[1][$i];
    }
    print_r($sentence);
    

    结果:

    Array
    (
        [0] => t
        [1] => e
        [2] => s
        [3] => t
        [4] => n
        [5] => e
        [6] => w
    )
    

    【讨论】:

    • 感谢克里斯蒂安。这也是一个很好的答案!我接受了另一个,因为该函数还允许指定添加字符串的偏移量。
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多