如何从字符串中删除字符?

时间:2010-06-01 04:00:16

标签: php string

(我的第一篇文章不清楚且令人困惑所以我编辑了这个问题)

我正在研究字符串操作。 您可以使用strlen()或substr(),但不能依赖库中预定义的其他函数。

给定字符串$string = "This is a pen",删除"is" 返回值为"Th a pen"(包括3个空格)。

删除'is'表示如果字符串是“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";
}

3 个答案:

答案 0 :(得分:2)

澄清,原来的静止不是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] = '',但这会在ThaTh[ ][ ]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] = '';

答案 1 :(得分:1)

如果你被允许使用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;
}

答案 2 :(得分:0)

以下代码也可用于替换子字符串:

$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;
}