显示标签为“php”的博文。显示所有博文
显示标签为“php”的博文。显示所有博文

2009/02/06

支持中文的截取字符函数,不同编码下中文字符的范围一目了然

有时候经常需要查找某个编码下中文字符的编码范围,下面这个函数一目了然,省事!

PHP语言: 中文截取

<?php
/*
* 中文截取,支持gb2312,gbk,utf-8,big5
*
* @param string $str 要截取的字串
* @param int $start 截取起始位置
* @param int $length 截取长度
* @param string $charset utf-8|gb2312|gbk|big5 编码
* @param $suffix 是否加尾缀
*/
public function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr"))
        return mb_substr($str, $start, $length, $charset);

    $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";

    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
   
    return $slice;
}
?>

2009/01/12

curl模拟浏览器抓取URL

使用php的curl模块,模拟浏览器行为,“E:/www/pachong/cookie.txt”为cookie存放的地方。curl默认输出为PHP的标准输出php://stdout,您也可以修改输出记录的磁盘文件。


<?php
set_time_limit(0);
ob_start();

$keyWords = rawurlencode("论语");

$url = 'http://www.amazon.cn/mn/searchApp?fea=layout&ix=sunray&keywords='.$keyWords.'&searchType=&showType=3&sortType=&node=0&searchKind=keyword&uid=168-5083975-3489864';

//初始化
$ch = curl_init();

curl_setopt($ch, CURLOPT_COOKIEJAR, "E:/www/pachong/cookie.txt");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; InfoPath.1; CIBA)");
curl_setopt($ch, CURLOPT_URL, $url);

//echo header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//mark this as a new cookie "session".
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
//echo body html
curl_setopt($ch, CURLOPT_NOBODY, FALSE);

//写入磁盘文件
/*
$outputFile = fopen("E:/www/pachong/contents.txt", 'ab');
curl_setopt($ch, CURLOPT_FILE, $outputFile);
*/

curl_exec($ch);

curl_close($ch);

$content = ob_get_clean();



echo '<pre>';
echo htmlspecialchars($content);
echo '</pre>';
?>

UTF8版的wordwrap()

wordwrap()发邮件有时候会用到之,php中原生的有时候会将汉字截断,它无法识别单字节和多字节,这里写了一个utf8版的。

<?php

function wordwrap_utf8( $string, $length=75, $break="\n", $cut=false) {
    preg_match_all("/./u", $string, $matches);
    $s = $matches[0];
    $ct = count( $s );
    for($i=0; $i<ceil($ct/$length) ; $i++) {
        $ns .= implode("", array_slice($s, $i*$length, $length) ) . $break;
    }
    return $ns;
}

?>


解决了wordwrap截断汉字的问题。缺点是$cut参数无法使用,会将英文单词截断。

如何保证程序唯一运行?

以前写过如何让php程序在后台运行,客户端触发,后台方式运行PHP程序 ,但某些场合要求我们此程序只能唯一运行,只跑一个。

解决办法:
1.使用文件锁来控制
2.创建目录
上述两个操作均可保证唯一性,当然还有其他办法,查找进程中是否有同名的进程之类,不太适合php。


<?php

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // 进行排它型锁定
    //do something
   
   
    flock($fp, LOCK_UN); // 释放锁定
} else {
    echo "Couldn't lock the file !";
    exit();
}

fclose($fp);

?>

2008/12/23

客户端触发,后台方式运行PHP程序

<?php
ob_start();

set_time_limit(0);

//run in background
ignore_user_abort(TRUE);


/* close browser connection */
$size = ob_get_length();
header("Connection: close");
header("Content-Length: $size");
ob_end_flush();
flush();

/**
* main
*/

//your code

?>



上面的程序只要客户端浏览器http请求即可触发,然后便主动断开浏览器连接,以后台方式继续运行。可以用在触发执行任务的场合。非常有用!

2008/12/10

PHP类型比较陷阱

<?php

//result is : bool(true)
var_dump( -1 == TRUE );

//result is : bool(true)
var_dump( "-1" == TRUE );

?>

结果让你困惑吧,其实就是判断值是否为0,“零为假,非零皆为真”,-1和‘-1’当然不为0了,所以就为true了。使用===时,上式均为false。

2008/11/26

php serialize and serialize SimpleXMLElement

在PHP5中,序列化/反序列化simpleXMLElement对象时发生Warning: unserialize() [function.unserialize]: Node no longer exists in...的错误。

查了一下,http://bugs.php.net/bug.php?id=46143&edit=1,里面有段描述:

AFAIK, you cannot serialize a SimpleXMLElement, because it's a resource wrapped inside an object and it would be impossible de restore thatresource upon unserialize()-ation. That's why you receive an error: theunserialized object doesn't know where's the original document anymore.Store it in text form instead (asXML()).
说是SimpleXMLElement这个对象内部是包装的资源,即php中的resource类型,而resource是不可以序列化的。

上述文字提供了一个解决方案,保存其xml字符串,然后再通过simplexml_load_file/simplexml_load_string恢复SimpleXMLElement对象即可,xml字符串可以通过SimpleXMLElement->asXML()得到。

2008/11/24

nusoap与php5内置soap模块类名冲突解决办法

Warning: SoapClient::SoapClient() expects parameter 2 to be array, boolean given in...

出现上述错误,原因是与php5内置soap模块类名冲突。

解决办法:
1.关闭php5的soap扩展。windows关掉extension=php_soap.dll即可,Ubuntu下apt-get install安装的没有此选项,只好重新编译。

2.(推荐此法)修改类名即可。将soapclient()改为nusoap_client(),soap_server()改为nusoap_server()。这样就永远不会发生冲突问题了。nusoap代码中有如下片段:

/**
* Backward compatibility
*/
class soap_server extends
nusoap_server {
}
/**
* For backwards compatiblity, define
soapclient unless the PHP SOAP extension is loaded.
*/
class soapclient
extends nusoap_client {
}

3.php5改为php4。

2008/11/11

SimpleXMLElement解析报错解决方案:剔除字符串中错误字符

实在不愿意写关于PHP乱码方面的东西了,今天再次遇到了一个很郁闷的问题,字符串中含有错误的字码(内码)。

报错:
Warning: SimpleXMLElement::__construct() [function.SimpleXMLElement---construct]:
input conversion failed due to input error, bytes 0xC2 0x2E 0x20 0x20 in
E:\www\alsobuy.php on line 47
PHP在解析XML文档时发生错误,这个问题很常见,主要是由于在xml文档中含有头部声明编码以外的字符,而php严格按照头部声明的编码来解析xml文档。通常都是GB2312编码发生此情况,我一般是使用正则来修改文档头部编码声明来避免。如下:
$xml = preg_replace("/(^<\?xml.*encoding.*)GB2312(.*\?>)/iU" ,
'${1}GBK${2}' , $xml );
一般将其修改为GBK即可,GB2312包含的汉字实在太少了。

今天却不好使,纳闷了,后来终于发现,该XML文档中含有一个错误字符,根本无法解析。

而在使用正则等处理字符串时,里面含有乱码一般不会报错,估计SimpleXmlElement()是堆栈来完成xml文档解析的,遇到错误字符就挂了。

解决方案:根据具体编码,确定字符内码的范围,遍历一遍,剔除错误的字符。

下面是根据GBK编码范围来剔除的,效果很好。

代码:
<?php
//含有两个错误的字符
$str = "我\x97\x7f鎔ㄅㄈ是德\x82\x09文";

$len = strlen($str);//长度
$new_str = "";

for($i=0; $i <= $len-1 ;$i++) { $s_hex = ord($str[$i]); if( $s_hex <= 0x7f && $s_hex >=0x00 )
{
//ACSII
$new_str .= $str[$i];
}
else if( $s_hex >= 0x81 && $s_hex <=0xfe )
{
//双字节
if( $i == $len-1 ) break;
$i++;
$s_hex = ord($str[$i]);
if( $s_hex >= 0x40 && $s_hex <= 0xfe && $s_hex != 0x7f)
{
$new_str .= $str[$i-1];
$new_str .= $str[$i];
}
}
}
echo $str.'<br/>';
echo $new_str.'<br/>';
?>



效果图:


方便看代码: