0

例子:

输入 = 2

文字 = aa bb cc

将变为:aa cc

位置的输入是 $_POST['position']

我有

$words = explode(" ", $_POST['string']);
for ($i=0; $i<count($words); $i++){ 
    echo $words[$i] . " ";
}
4

5 回答 5

2
$to_remove = 2;
$text = "aa bb cc";

$words = explode(' ', $text);
if(isset($words[$to_remove -1])) unset($words[$to_remove -1]);
$text = implode(' ', $words);
于 2013-06-18T19:49:26.493 回答
0
$input = 2;
$words = explode(" ", $_POST['string']);
unset($words[$input-1]);
$words = implode(" ", $words);
echo $words;
于 2013-06-18T19:51:03.090 回答
0

这听起来像是一个家庭作业问题。不过,我会尝试一下:

代码:

<?php
    $string = trim($_POST['string']);
    $parts = explode(" ", string);
    $newString = "";
    $position = intval($_POST['position']);
    for($a = 0; $a < count($parts); $a++) {
        if($a != $position) { // or $a != ($position - 1) depending on if you passed in zero based position
            $newString = $newString . $parts[$a] . " ";
        }
    }
    $newString = trim($newString);

    echo "Old String: " . $string . "<br />";
    echo "New String: " . $newString;
?>

输出:

Old String: aa bb cc
New String: aa cc
于 2013-06-18T19:52:35.043 回答
0

拔出大枪REGEX !!!

$string = 'aa bb cc dd';
$input = 2;

$regex = $input - 1;
echo preg_replace('#^((?:\S+\s+){'.$regex.'})(\S+\s*)#', '$1', $string);

输出: aa cc dd

于 2013-06-18T19:53:57.257 回答
0

Foreach 循环往往使它更容易理解(IMO)。看起来也更干净。

$pos = 2;
$sentence = explode(" ", $_POST['string']);

foreach ($sentence as $index => $word) {
    if ($index != $pos - 1) {
        $result .= $word . ' ';
    }
}

echo $result;
于 2013-06-18T19:56:31.470 回答