欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

常用字符串处理代码片段

程序员文章站 2022-06-13 17:56:23
...
  移除 HTML 标签
  1. $text = strip_tags($input, "");

  返回 $start 和 $end 之间的文本

  1. function GetBetween($content,$start,$end){
  2. $r = explode($start, $content);
  3. if (isset($r[1])){
  4. $r = explode($end, $r[1]);
  5. return $r[0];
  6. }
  7. return '';
  8. }

  将url转换成链接

  1. $url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
  2. $url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);

  切分字符串为140个字符

  1. function split_to_chunks($to,$text){
  2. $total_length = (140 - strlen($to));
  3. $text_arr = explode(" ",$text);
  4. $i=0;
  5. $message[0]="";
  6. foreach ($text_arr as $word){
  7. if ( strlen($message[$i] . $word . ' ') $total_length ){
  8. if ($text_arr[count($text_arr)-1] == $word){
  9. $message[$i] .= $word;
  10. } else {
  11. $message[$i] .= $word . ' ';
  12. }
  13. } else {
  14. $i++;
  15. if ($text_arr[count($text_arr)-1] == $word){
  16. $message[$i] = $word;
  17. } else {
  18. $message[$i] = $word . ' ';
  19. }
  20. }
  21. }
  22. return $message;
  23. }

  删除字符串中的URL

  1. $string = preg_replace('/\b(https?ftpfile):\/\/[-A-Z0-9+&@#\/%?=~_$!:,.;]*[A-Z0-9+&@#\/%=~_$]/i', '', $string);

  将字符串转成SEO友好的字符串

  1. function slug($str){
  2. $str = strtolower(trim($str));
  3. $str = preg_replace('/[^a-z0-9-]/', '-', $str);
  4. $str = preg_replace('/-+/', "-", $str);
  5. return $str;
  6. }

  解析 CSV 文件

  1. $fh = fopen("contacts.csv", "r");
  2. while($line = fgetcsv($fh, 1000, ",")) {
  3. echo "Contact: {$line[1]}";
  4. }

  字符串搜索

  1. function contains($str, $content, $ignorecase=true){
  2. if ($ignorecase){
  3. $str = strtolower($str);
  4. $content = strtolower($content);
  5. }
  6. return strpos($content,$str) ? true : false;
  7. }

  检查字符串是否以某个串开始

  1. function String_Begins_With($needle, $haystack {
  2. return (substr($haystack, 0, strlen($needle))==$needle);
  3. }

  从字符串中提取email地址

  1. function extract_emails($str){
  2. // This regular expression extracts all emails from a string:
  3. $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
  4. preg_match_all($regexp, $str, $m);
  5. return isset($m[0]) ? $m[0] : array();
  6. }
  7. $test_string = 'This is a test string...
  8. test1@example.org
  9. Test different formats:
  10. test2@example.org;
  11. "test3@example.org">foobar