php中常用字符串处理代码片段整理
2015-01-24信息快讯网
php中常用字符串处理代码片段,使用php的朋友可以参考下。
移除 HTML 标签
$text = strip_tags($input, "");
上面的函数主要是使用了strip_tags,具体的使用说明参考。
返回 $start 和 $end 之间的文本
function GetBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
将url转换成链接
$url = "Jean-Baptiste Jung (http://www.jb51.net)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '<a href="http://www.catswhocode.com/blog/$1" style="font-size: 12px; vertical-align: baseline; background-color: transparent; margin: 0px; padding: 0px; color: #3777af; text-decoration: none; font-weight: bold">$0</a>', $url);
切分字符串为140个字符
function split_to_chunks($to,$text){
$total_length = (140 - strlen($to));
$text_arr = explode(" ",$text);
$i=0;
$message[0]="";
foreach ($text_arr as $word){
if ( strlen($message[$i] . $word . ' ') <= $total_length ){
if ($text_arr[count($text_arr)-1] == $word){
$message[$i] .= $word;
} else {
$message[$i] .= $word . ' ';
}
} else {
$i++;
if ($text_arr[count($text_arr)-1] == $word){
$message[$i] = $word;
} else {
$message[$i] = $word . ' ';
}
}
}
return $message;
}
删除字符串中的URL
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
将字符串转成SEO友好的字符串
function slug($str){
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
return $str;
}
解析 CSV 文件
$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
echo "Contact: {$line[1]}";
}
字符串搜索
function contains($str, $content, $ignorecase=true){
if ($ignorecase){
$str = strtolower($str);
$content = strtolower($content);
}
return strpos($content,$str) ? true : false;
}
检查字符串是否以某个串开始
function String_Begins_With($needle, $haystack {
return (substr($haystack, 0, strlen($needle))==$needle);
}
从字符串中提取email地址
function extract_emails($str){
// This regular expression extracts all emails from a string:
$regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
preg_match_all($regexp, $str, $m);
return isset($m[0]) ? $m[0] : array();
}
$test_string = 'This is a test string...
[email protected]
Test different formats:
[email protected];
<a href="[email protected]">foobar</a>
<[email protected]>
strange formats:
[email protected]
test6[at]example.org
[email protected]
test8@ example.org
test9@!foo!.org
foobar
';
print_r(extract_emails($test_string));
基于php socket(fsockopen)的应用实例分析
深入PHP操作MongoDB的技术总结
深入php数据采集的详解
基于php下载文件的详解
用PHP实现浏览器点击下载TXT文档的方法详解
基于PHP字符串的比较函数strcmp()与strcasecmp()的使用详解
PHP字符串的编码问题的详细介绍
str_replace只替换一次字符串的方法
PHP 数组和字符串互相转换实现方法
PHP字符过滤函数去除字符串最后一个逗号(rtrim)
php数组函数序列之in_array() - 查找数组中是否存在指定值
php smarty截取中文字符乱码问题?gb2312/utf-8
PHP面向对象概念
php 记录进行累加并显示总时长为秒的结果
php 按指定元素值去除数组元素的实现方法
php数组函数序列之array_search()- 按元素值返回键名
php中判断字符串是否全是中文或含有中文的实现代码
php将时间差转换为字符串提示
php中将图片gif,jpg或mysql longblob或blob字段值转换成16进制字符串
php中计算中文字符串长度、截取中文字符串的函数代码
php中将时间差转换为字符串提示的实现代码