PHP 在特定位置向字符串添加文本 - 问题
PHP add text to string at certain positions -issue
我试图在某些位置插入文本到字符串(在这种情况下是字母 "b" 之前),但出于某种原因,我只在最后 position/occurance。
<?php
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($str, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
for ($i=0;$i<count($positions);$i++) {
$newstring = substr_replace($str,$teststr,$positions[$i],0);
}
echo $newstring;
?>`
这会产生以下输出:aabaaaaabaaaaa test b
当所需的是: aa test aaaaa test aaaaa test b
正则表达式对你有用吗?
<?php
$str = "aabaaaaabaaaaab";
echo preg_replace('~b~', ' test b', $str);
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = explode($needle, $str);
foreach($positions as $k=>$v) {
$positions[$k]=$v.$teststr.$needle;
}
$positions=implode($positions);
echo $positions;
试试这个
您使用 $str
作为 substring_replace
的输入,但您没有在任何地方修改 $str
。显然只有最后一个替换会显示。例如,您可以使用 $newstring
作为 substring_replace
的输入,但这样您的位置就不再正确了。这可以通过从右到左进行替换来避免:
//snip
$newstring = $str;
for ($i = count($positions) - 1; $i >= 0; $i--) {
$newstring = substr_replace($newstring, $teststr, $positions[$i], 0);
}
echo $newstring;
以下应该有效
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
for ($i=0;$i<strlen($str);$i++) {
if($str[$i]==$needle ){
echo $teststr.$str[$i];
}else{
echo $str[$i];
}
}
echo $newstring;
**Output**
aa test baaaaa test baaaaa test b
我试图在某些位置插入文本到字符串(在这种情况下是字母 "b" 之前),但出于某种原因,我只在最后 position/occurance。
<?php
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($str, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
for ($i=0;$i<count($positions);$i++) {
$newstring = substr_replace($str,$teststr,$positions[$i],0);
}
echo $newstring;
?>`
这会产生以下输出:aabaaaaabaaaaa test b 当所需的是: aa test aaaaa test aaaaa test b
正则表达式对你有用吗?
<?php
$str = "aabaaaaabaaaaab";
echo preg_replace('~b~', ' test b', $str);
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = explode($needle, $str);
foreach($positions as $k=>$v) {
$positions[$k]=$v.$teststr.$needle;
}
$positions=implode($positions);
echo $positions;
试试这个
您使用 $str
作为 substring_replace
的输入,但您没有在任何地方修改 $str
。显然只有最后一个替换会显示。例如,您可以使用 $newstring
作为 substring_replace
的输入,但这样您的位置就不再正确了。这可以通过从右到左进行替换来避免:
//snip
$newstring = $str;
for ($i = count($positions) - 1; $i >= 0; $i--) {
$newstring = substr_replace($newstring, $teststr, $positions[$i], 0);
}
echo $newstring;
以下应该有效
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
for ($i=0;$i<strlen($str);$i++) {
if($str[$i]==$needle ){
echo $teststr.$str[$i];
}else{
echo $str[$i];
}
}
echo $newstring;
**Output**
aa test baaaaa test baaaaa test b