How does php intercept strings according to utf8 coding rules
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: