PHP 函数,用于删除字符串中某些字符之间的所有字符

2022-08-30 13:13:08

我感兴趣的是,这将在给定$string中搜索$char 1和$char 2,如果发现这种情况,可以从这两个字符之间的子字符串中清除$string,包括$char 1和$char 2本身。function delete_all_between($char1, $char2, $string)

例:

$string = 'Some valid and <script>some invalid</script> text!';
delete_all_between('<script>', '</script>', $string);

现在,$string应该只包含

'Some valid and  text'; //note two spaces between 'and  text'

有人有快速的解决方案吗?


答案 1
<?php

$string = 'Some valid and <script>some invalid</script> text!';
$out = delete_all_between('<script>', '</script>', $string);
print($out);

function delete_all_between($beginning, $end, $string) {
  $beginningPos = strpos($string, $beginning);
  $endPos = strpos($string, $end);
  if ($beginningPos === false || $endPos === false) {
    return $string;
  }

  $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

  return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
}

答案 2

下面是一个单行线:

preg_replace('/START[\s\S]+?END/', '', $string);

替换和:)学分转到另一个SO线程!STARTEND


推荐