PHP字符串处理常用函数与技巧
1. 获取字符串长度
$text = "sunny day";
$count = strlen($text); // $count = 92. 截取字符串
截取指定长度的字符
$article = "BREAKING NEWS: In ultimate irony, man bites dog."; $summary = substr_replace($article, "...", 40);3. 统计单词数量
$article = "BREAKING NEWS: In ultimate irony, man bites dog."; $wordCount = str_word_count($article);
// $wordCount = 84. 将URL转换为HTML链接
$url = "W.J. Gilmore, LLC (https://www.jb51.net)";
$url = preg_replace("/http://([A-z0-9./-]+)/", "$0", $url);5. 去除字符串中的HTML标签
$text = strip_tags($input, "<p><br>");"); 6. nl2br函数:
$comment = nl2br($comment);将换行符转换为HTML的<br>标签
7. Wordwrap:
限制每行的字符数
$speech = "Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.";
echo wordwrap($speech, 30);输出结果如下:
Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.