php汉字的截取完美解决方案
作者: 火车头 日期: 2008-07-15 11:23
php汉字的截取完美解决方案 函数巧妙地运用了正则表达式, 用起来很方便, 就像 substr 的用法一样, 可以正向截取也可反相截取, 思路值得学习.
函数巧妙地运用了正则表达式, 用起来很方便, 就像 substr 的用法一样, 可以正向截取也可反相截取, 思路值得学习.
PHP代码:
- <?php
- function c_substr($string, $from, $length = null){
- }else{
- }
- return $result;
- }
- $str = "zhon华人min共和guo";
- $from = 3;
- $length = 7;
- // 输出: n华人min共
- //还有utf-8的
- /*
- Regarding windix's function to handle UTF-8 strings:
- one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8
- (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32).
- This way the function works for other encodings too (like Greek for example).
- The modified function would read like this:
- */
- function utf8_substr($str,$start) {
- $null = "";
- } else {
- }
- }
- ?>
之二:
- <?php
- /***************************************************/
- /* */
- /* Author: */
- /* HomePage: www..com */
- /* Email: phforum@163.com */
- /* QQ:1984412 */
- /* */
- /***************************************************/
- function get_substr($string,$start='0',$length='')
- {
- $start = (int)$start;
- $length = (int)$length;
- $i = 0;
- if(!$string)
- {
- return;
- }
- if($start>=0)
- {
- while($i<$start)
- {
- {
- $i = $i+2;
- }
- else
- {
- $i++;
- }
- }
- $start = $i;
- if($length=='')
- {
- }
- elseif($length>0)
- {
- $end = $start+$length;
- while($i<$end)
- {
- {
- $i = $i+2;
- }
- else
- {
- $i++;
- }
- }
- if($end != $i-1)
- {
- $end = $i;
- }
- else
- {
- $end--;
- }
- $length = $end-$start;
- }
- elseif($length==0)
- {
- return;
- }
- else
- {
- return get_substr($string,$start,$length);
- }
- }
- else
- {
- return get_substr($string,$start,$length);
- }
- }
- ?>
评论: 0 |
引用: 0 |
阅读: 1138
发表评论
订阅
上一篇
返回
下一篇