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

时间:2012-10-23 13:14:01

标签: php string

我对function delete_all_between($char1, $char2, $string)感兴趣 将为$ char1和$ char2搜索$ string,如果已找到,则清除这两个字符之间子串的$ string,包括 $ char1和$ char2本身。

示例:

$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'

有人有快速解决方案吗?

7 个答案:

答案 0 :(得分:48)

<?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
}

答案 1 :(得分:18)

这是一个oneliner:

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

替换STARTEND :)积分转到另一个SO帖子!

答案 2 :(得分:2)

我认为substr()的效果太慢了。最好的方法是:

return substr($string, 0, $beginningPos) . 
       substr($string, $endPos + strlen($end));

答案 3 :(得分:1)

实际上,我正在寻找一个功能,它为我提供了简单而稳定的解决方案来获取TWIG模板的所有变量。 由于许多原因,提议的regexp运行不正常,所以我决定只删除标签之间的所有内容而不是计算标签^ _ ^。

/**
     * deletes ALL the string contents between all the designated characters
     * @param $start - pattern start 
     * @param $end   - pattern end
     * @param $string - input string, 
     * @return mixed - string
     */
    function auxDeleteAllBetween($start, $end, $string) {
        // it helps to assembte comma dilimited strings
        $string = strtr($start. $string . $end, array($start => ','.$start, $end => chr(2)));
        $startPos  = 0;
        $endPos = strlen($string);
        while( $startPos !== false && $endPos !== false){
            $startPos = strpos($string, $start);
            $endPos = strpos($string, $end);
            if ($startPos === false || $endPos === false) {
                $run = false;
                return $string;
            }
            $textToDelete = substr($string, $startPos, ($endPos + strlen($end)) - $startPos);
            $string = str_replace($textToDelete, '', $string);
        }
        return $string;
    }

    /**
     * This function is intended to replace
     * //preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $this->_tplSubj, $matchesSubj);
     * which did not give intended results for some reason.
     *
     * @param $inputTpl
     * @return array
     */
    private function auxGetAllTags($inputTpl){
        $inputTpl = strtr($inputTpl, array('}}' => ','.chr(1), '{{' => chr(2)));
        return explode(',',$this->auxDeleteAllBetween(chr(1),chr(2),$inputTpl));
    }


$template = '<style>
td{border-bottom:1px solid #eee;}</style>
<p>Dear {{jedi}},<br>New {{padawan}} is waiting for your approval: </p>
<table border="0">
<tbody><tr><td><strong>Register as</strong></td><td>{{register_as}}, user-{{level}}</td></tr>
<tr><td><strong>Name</strong></td><td>{{first_name}} {{last_name}}</td></tr>...';

print_r($this->auxGetAllTags($template));

答案 4 :(得分:1)

就我而言,first 版本有问题,这是我更正的版本(如果 $end 字符串也出现在 $beginning 字符串之前)

<?php 
$string = 'Some </script> 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);
    $tmpstring = substr($string, $beginningPos);  
    $endPos = strpos($tmpstring, $end);
    if ($beginningPos === false || $endPos === false) {
        return $string;
    }
    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) );
    return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
}

答案 5 :(得分:0)

你可以使用双str_replace() $q = str_replace('<script>', '', $string); $p = str_replace('some invalid', '', $q); echo $p;

答案 6 :(得分:0)

我想删除 php 中的标签,因为我想在将 html 解析为 DOMDocument 之前删除未使用的标签。

这是我使用的代码。 光标在开始情况下为 0。只是在程序中用于递归。

function delete_all_betweenV2($cursor, $beginning, $end, $string, $retainSelf) {
    echo '>>>> Start '.'<br>';
    $beginningPos = strpos($string, $beginning, $cursor);
    $endPos = strpos($string, $end, $beginningPos);
    
    if ($beginningPos === false || $endPos === false) {
      echo '>>>> End '.'<br>';
      return $string;
    }    
    
    if($endPos >= strlen($string)) {
      echo '>>>> End '.'<br>';
      return $string;
    }
    
    $lenOfBeginning = strlen($beginning);
    $lenOfEnd = strlen($end);
    
    $result = $string;
    if($retainSelf) {
      echo 'b4 input String: '.$string.'<br>';
      echo 'b4 cursor = : '.$cursor. '<br>';
      echo 'b4 string: '.$string. '<br>';
      echo 'b4 beginning Pos: '.$beginningPos.'<br>';
      echo 'b4 end Pos: '.$endPos.'<br>';
      echo 'b4 length to be cut is: '.(($endPos - $lenOfEnd) - $beginningPos).'<br>';
      
      if($cursor > 0) {
        echo 'cursor is greater than 0'.'<br>';
        $textToDelete = substr($string, $beginningPos + $lenOfBeginning, ($endPos - $lenOfEnd) - $beginningPos);
      } else {
        echo 'cursor is NOT greater than 0'.'<br>';
        $textToDelete = substr($string, $beginningPos + $lenOfBeginning, ($endPos - $lenOfEnd) - $beginningPos);
      }
      
      echo 'TextToDelete:'.$textToDelete.'<br>';
        
      //$stringStart = substr($string, 0, $beginningPos + $lenOfBeginning);
      //echo $stringStart.'<br>';
      //$stringTail = substr($string, $endPos, strlen($string));
      //echo $stringTail.'<br>';    
      $result = str_replace($textToDelete, '', $string);
      $cursor = $beginningPos + $lenOfBeginning; // just make sure that the cursor search next character/word
      echo 'After cursor = : '.$cursor. '<br>';
      echo 'After result: '.$result. '<br>';
      echo 'After len of result: '.strlen($result). '<br>';
    } else {
        //$stringStart = substr($string, 0, $beginningPos);
        //echo $stringStart.'<br>';
        //$stringTail = substr($string, $endPos + $lenOfEnd, strlen($string));
        //echo $stringTail.'<br>';
        $cursor = 0;
        
        $textToDelete = substr($string, $beginningPos, ($endPos + $lenOfEnd) - $beginningPos);
        echo 'TextToDelete:'.$textToDelete.'<br>';
        $result = str_replace($textToDelete, '', $string);
    } 
    echo '>>>> End '.'<br>';
    return delete_all_betweenV2($cursor, $beginning, $end, $result, $retainSelf);
}