Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does php intercept strings according to utf8 coding rules

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces php how to intercept strings according to utf8 coding rules, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

The code is as follows:

/ *

* function: the function is the same as substr, except that it does not cause garbled code.

* parameters:

* return:

, /

Function utf8_substr ($str, $start, $length=null) {

/ / first intercept normally.

$res = substr ($str, $start, $length)

$strlen = strlen ($str)

/ * then judge whether the 6 bytes of each head and tail are complete (not incomplete) * /

/ / if the parameter start is positive

If ($start > = 0) {

/ / intercept about 6 bytes further

$next_start = $start + $length; / / initial location

$next_len = $next_start + 60? $start-6: 0

$prev_segm = substr ($str, $prev_start, $start-$prev_start)

}

/ / start is negative

Else {

/ / intercept about 6 bytes further

$next_start = $strlen + $start + $length; / / initial location

$next_len = $next_start + 60? $start-6: 0

$prev_segm = substr ($str, $prev_start, $start-$prev_start)

}

/ / determine whether the first 6 bytes conform to utf8 rules

If (preg_match ('@ ^ ([\ x80 -\ xBF] {0Magne5}) [\ xC0-\ xFD]? @', $next_segm, $bytes)) {

If (! empty ($bytes [1])) {

$bytes = $bytes [1]

$res. = $bytes

}

}

/ / determine whether the last 6 bytes conform to utf8 rules

$ord0 = ord ($res [0])

If (128 = $ord0) {

/ / intercept it back and add it in front of the res.

If (preg_match ('@ [\ xC0-\ xFD] [\ x80 -\ xBF] {0 5} $@', $prev_segm, $bytes)) {

If (! empty ($bytes [0])) {

$bytes = $bytes [0]

$res = $bytes. $res

}

}

}

Return $res

}

Test data:

The copy code is as follows:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report