[英]How to remove characters from a string?
(我的第一篇文章不清楚且令人困惑,所以我編輯了問題)
我正在研究字符串操作。 您可以使用strlen()或substr(),但不能依賴庫中預定義的其他函數。
給定字符串$string = "This is a pen"
,請刪除"is"
以使返回值為"Th a pen"
(包括3個空格)。
刪除“是”表示如果字符串為“ Tsih”,我們不會將其刪除。 僅刪除“是”。
我已經嘗試過(如下所示),但是返回的值不正確。 我已經進行了測試,但仍在捕獲定界符。
提前致謝!
function remove_delimiter_from_string(&$string, $del) {
for($i=0; $i<strlen($string); $i++) {
for($j=0; $j<strlen($del); $j++) {
if($string[$i] == $del[$j]) {
$string[$i] = $string[$i+$j]; //this grabs delimiter :(
}
}
}
echo $string . "\n";
}
澄清一下,原始問題不是Implement a str_replace
,而是remove 'is' from 'this is a pen' without any functions and no extra white spaces between words
。 最簡單的方法將是$string[2] = $string[3] = $string[5] = $string[6] = ''
但是這將留下之間的多余的空白Th
和a
( Th[ ][ ]a
)。
隨您去,根本沒有任何功能
$string = 'This is a pen';
$word = 'is';
$i = $z = 0;
while($string[$i] != null) $i++;
while($word[$z] != null) $z++;
for($x = 0; $x < $i; $x++)
for($y = 0; $y < $z; $y++)
if($string[$x] === $word[$y])
$string[$x] = '';
如果您被允許使用substr(),那就容易多了。 然后,您可以循環播放並檢查匹配的值,為什么不能使用substr()但可以使用strlen()呢?
但是,如果沒有,它至少起作用:
echo remove_delimiter_from_string("This is a pen","is");
function remove_delimiter_from_string($input, $del) {
$result = "";
for($i=0; $i<strlen($input); $i++) {
$temp = "";
if($i < (strlen($input)-strlen($del))) {
for($j=0; $j<strlen($del); $j++) {
$temp .= $input[$i+$j];
}
}
if($temp == $del) {
$i += strlen($del) - 1;
} else {
$result .= $input[$i];
}
}
return $result;
}
以下代碼也可以用來替換子字符串:
$restring = replace_delimiter_from_string("This is a pen","is", "");
var_dump($restring);
$restring = replace_delimiter_from_string($restring," ", " ");
var_dump($restring);
function replace_delimiter_from_string($input, $old, $new) {
$input_len = strlen($input);
$old_len = strlen($old);
$check_len = $input_len-$old_len;
$result = "";
for($i=0; $i<=$check_len;) {
$sub_str = substr($input, $i, $old_len);
if($sub_str === $old) {
$i += $old_len;
$result .= $new;
}
else {
$result .= $input[$i];
if($i==$check_len) {
$result = $result . substr($input, $i+1);
}
$i++;
}
}
return $result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.