Home  >  Article  >  Backend Development  >  PHP implements interception of Chinese strings without appearing

PHP implements interception of Chinese strings without appearing

高洛峰
高洛峰Original
2017-01-21 13:35:561296browse

The example in this article describes the solution of PHP intercepting Chinese strings without the ? sign. Share it with everyone for your reference, the details are as follows:

When PHP intercepts a mixed string of Chinese and English, the last Chinese character is often split into two halves, for example: intercepting the first 18 characters of the string

<?php
$text = "1欢迎访问sina新浪播客";
$value = substr($text, 0, 18);
echo $value."<BR>";
?>

The output is:

1欢迎访问新浪?BR>

So I wrote the following code to determine if the number of Chinese character bytes in a mixed Chinese and English string is an odd number , then one less byte will be intercepted to ensure complete display of Chinese characters.

<?php
$text = "1欢迎访问sina新浪播客";
$value = substr($text, 0, 18);
$value_length = strlen($value);
$value_count = 0;
for ($i = 0; $i < $value_length; $i++)
{
  if (ord($value{$i}) > 127)
  {
    $value_count++;
  }
}
if ($value_count % 2 != 0)
{
  $value = substr($text, 0, $value_length - 1);
}
echo $value."<BR>";
?>


The output is:

1欢迎访问sina新浪

I hope this article will be useful to everyone in PHP programming. helped.

For more related articles on PHP implementation of intercepting Chinese strings without appearing, please pay attention to the PHP Chinese website!

Statement:
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