Home  >  Article  >  Backend Development  >  PHP interception string function (Chinese string) (1/2)_PHP tutorial

PHP interception string function (Chinese string) (1/2)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:57:54895browse

php interception string function (Chinese string) This is a PHP string interception function. It supports Chinese strings. It can intercept mixed content such as HTML and Chinese and Western texts, and the HTML tag is not included in the character interception. If the HTML tag does not Closed, the program will automatically filter out redundant tags.

php tutorial interception string function (Chinese string)
This is a PHP string interception function. It supports Chinese strings. It can intercept mixed content such as HTML and Chinese and Western texts, and the HTML tag is not included in the character interception. If the HTML tag does not Closed, the program will automatically filter out redundant tags.
*/

function mysubstr( $str, $length ){
 
$tagcnt = 0;
$charcnt = 0;
$tag = '';
$maxlen = strlen( $str );
$resultstr = '';
$tagstack = array();

for( $i = 0; $i < $length; $i++ ){
           if( $str[$i] == '<' ){

$resultstr .= $str[$i];

for( $j=$i; $str[$j]!='>'; $j++,$length++ ){
                      $tag .= $str[$j];
            }
               $tagcnt++;
              $length++;
                 $tag .= '>';
                                                                                                    // If it is a start tag, push it onto the stack, if it is a corresponding end tag, pop it out of the stack
If( preg_match('/<([^/]+)?>/i', $tag, $r) ){
Echo 'into the stack:', htmlspecialchars ($ r [1]), '& lt; br /& gt;';
                    array_push($tagstack, $r[1]);
            }
                elseif( preg_match( '/'.$tagstack[count($tagstack)-1].'/', $tag ) ){
Echo 'out of the stack:', htmlspecialchars ($ tagstack [count ($ tagstack) -1]), '& lt; br /& gt;';
                    array_pop( $tagstack);
            }

$tag = '';

                continue;
}

$charcnt++;

          $resultstr .= $str[$i];
}

echo '


The final result is:';

//The stack is empty and returns directly

If(empty($tagstack)){
          return $resultstr;
}
//Otherwise remove the start tag without end tag
else{
         
​​​​while(!empty($tagstack)){

$tag = array_pop($tagstack);

$index = strrpos($resultstr, $tag);

for($i = $index-1; $resultstr[$i] != '>'; $i++ ){

                    $resultstr[$i] = '';
            }

$resultstr[$i++] = '';

         
}

return $resultstr;

}
 
}

$sttime = microtime(true);

$stmem = memory_get_usage();

$str = "a1b2

c3d4e5

f6g7h8";

echo 'The processing result is:


',htmlspecialchars( mysubstr( $str, 18 ) ),'
';

echo "Memory usage:",(memory_get_usage()-$stmem),'
';

echo "Algorithm running time (microtime):",(microtime(true)-$sttime),'
';

//Method 2

/

**
* Function name html_substr
* Function: intercept a string of specified length from the html string, html tags are not included
* Parameter
* $str The string to be intercepted
* $len The length to be intercepted
* $mode processing method of unmatched tags 0 deletes (default), 1 completes
* Return the intercepted string
* Description
* Multi-byte characters are not considered, only bytes are used as the counting unit
* Marks that can exist alone are not considered
**/
function html_substr($str, $len, $mode=0) {
$ar= preg_split('/(|<[^>]*>)/s', $str, -1, preg_split_delim_capture);
foreach($ar as $k => $v) {
If($v{0} != '<') {
$len = $len - strlen($v);
If($len < 0) $ar[$k] = substr($v, 0, $len);
}else $ar[$k] = strtolower($v);
If($len <= 0) break;
}
$ar = array_slice($ar, 0, $k+1);
$len = count($ar);
foreach($ar as $k=>$v) {
If($v{0} == '<' && $v[1] != '/') {
$ch = str_replace('<', ' for($i=$k+1; $i<$len && $ar[$i]!=$ch; $i++);
If($i == $len)
          if($mode)
$ar[$len] = $ch . $ar[$len];
        else
             $ar[$k] = '';
}
}
return join('', $ar);
}
$str = "123abc456def789";

echo '

';<br> echo html_substr($str, 5) .php_eol;<br> echo html_substr($str, 5, 1);</p> </blockquote> <p> 1 2 </p> <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/632042.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/632042.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">php intercept string function (Chinese string) This is a php intercept string function, this is a This model supports Chinese strings. It can intercept mixed content such as HTML, Chinese and Western texts, etc...</span> </div> <div class="art_confoot"></div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="php ajax examples and ajax tutorial_PHP tutorial" href="https://m.php.cn/faq/298354.html">php ajax examples and ajax tutorial_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="php ajax examples and ajax tutorial_PHP tutorial" href="https://m.php.cn/faq/298356.html">php ajax examples and ajax tutorial_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>