删除字符串的第一个和最后一个实例?

时间:2010-06-29 22:37:56

标签: php string

如何从字符串中删除某段html的第一个实例。

我想删除

      </tr>
    </table></td>

  </tr

接近开始,但它也出现在整个字符串中。

我还需要一种方法来做同样的事情,但最后的实例。

有人知道吗?

4 个答案:

答案 0 :(得分:2)

如果您大致知道要替换的子字符串与字符串末尾的接近程度,那么您使用substr_replace()的参数为负$start$length,或者您可以只需手动编写一个函数来实际执行,找到最后一个匹配项,然后删除它。这样的事情(未经测试,写得非常快):

function replace_last_occurrence($haystack, $needle) {
    $pos = 0;
    $last = 0;

    while($pos !== false) {
        $pos = strpos($haystack, $needle, $pos);
        $last = $pos;
    }

    substr_replace($haystack, "", $last, strlen($needle));
}

类似,第一次出现

function replace_first_occurrence($haystack, $needle) {        
    substr_replace($haystack, "", strpos($haystack, $needle, $pos), 
        strlen($needle));
}

您也可以将其概括为替换第n次出现:

function replace_nth_occurrence($haystack, $needle, $n) {
    $pos = 0;
    $last = 0;

    for($i = 0 ; $i <= $n ; $i++) {
        $pos = strpos($haystack, $needle, $pos);
        $last = $pos;
    }

    substr_replace($haystack, "", $last, strlen($needle));
}

答案 1 :(得分:1)

最简单的方法是爆炸/拆分字符串移位顶部然后弹出最后一个然后内爆你剩下的东西是分隔符并连接三个......即:

$separator = 'your specified html separator here';
$bits = explode($separator , $yourhtml );
$start = array_shift($bits);
$end = array_pop($bits);
$sorted = $start . implode($separator,$bits) . $end;

(未经测试)

答案 2 :(得分:1)

这将删除最后一次出现:

$needle = <<<EON
    </tr>
  </table></td>

</tr
EON;

if(preg_match('`.*('.preg_quote($needle).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) {
  $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}

作为额外奖励,您可以忽略搜索片段中不同数量的空格,如下所示:

if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) {
  $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}

甚至通过向regexp添加i-flag来搜索不区分大小写:

if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`is', $haystack, $m, PREG_OFFSET_CAPTURE)) {
  $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}

答案 3 :(得分:-3)

你会想要str_replace。用空格替换该部分(例如:“”)