Reputation: 4189
If I have a string like "test", I have characters from offset 0-3. I would like to add another string to this one at offset 6. Is there a simple PHP function that can do this?
I am trying this, but getting an error:
PHP Fatal error: Cannot use assign-op operators with overloaded objects nor string offsets in ...
I understand I could concatenate these strings, but I want to build a sentence based on output from Stanford CoreNLP that provides string offset locations http://nlp.stanford.edu/software/example.xml (more info at 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 docs say at 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.
Upvotes: 2
Views: 1884
Reputation: 402
Convert the string to an array, in the case where the offset is greater than the string length fill in the missing indexes with a padding character of your choice otherwise just insert the string at the corresponding array index position and implode the string array.
Please see the function below:
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);
Upvotes: 2
Reputation: 2097
To solve your problem first of all you convert your strings in arrays with str_split
, then when you've got the array you're done, you can perform any kind of operations on these strings.
Code:
$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);
Result:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
[4] => n
[5] => e
[6] => w
)
Upvotes: 1