如果我有一个像“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/