php intercept string function substr iconv_substr mb_substr examples and pros and cons analysis

  • 2021-06-28 11:57:08
  • OfStack

Sample code, using functions substr and iconv_substr, mb_substr


<html>
<head><meta charset='utf-8'>
<title> Intercept Chinese String _ Script Home _www.ofstack.com</title>
</head>
<body>
<?php
$str='123 Script Home 456 Welcome to ';
echo substr($str,0,4);
echo '<br>';
echo iconv_substr($str,0,4,'utf-8');
echo '<br>';
echo mb_substr($str,0,4,'utf-8');
?>
</body>
</html>

Explain:
The above code uses two functions, iconv_substr and mb_substr, can be used for string Interception under the current character to achieve Chinese character interception without scrambling code.

How should I choose?

1. The iconv library may not work correctly on some operating systems. The GNU extension library needs to be installed to ensure its normal operation.mb_The substr function is more compatible.

2. The iconv function converts the current string to the corresponding encoding before intercepting, while the mb function intercepts directly from the specified encoding (providing a secure multibyte intercept), so the mb function is more efficient to intercept.

Therefore, mb_The substr function intercepts Chinese strings as the most appropriate choice.


Related articles: