PHP字符串处理的10个简单方法

2019-04-09 18:07:00王冬梅


$url = "W.J. Gilmore, LLC (http://www.wjgilmore.com)";
$url = preg_replace("/http://([A-z0-9./-]+)/", "$0", $url);
// $url = "W.J. Gilmore, LLC (http://www.wjgilmore.com)"

7.从一个字符串中去除HTML标签

作为Web开发人员,其中的一个主要工作就是要确保用户输入中不含有危险字符,如果有,这会导致SQL注入或脚本攻击。PHP语言中包含了很多安全方面的功能,这些功能能够帮助你过滤数据,包括延长过滤器。例如,你可以允许用户中带有一些基本的HTML语句,包括一些注释。实现这个功能,你可以使用带有检查功能函数:strip_tags()。它在默认的情况下是从字符串中删除所有的HTML标签,但同时也允许覆盖默认或者你指定的标签。例如,在下面的例子中,你可以除去所有的标签:

$text = strip_tags($input, " ");

8.比较两个字符串

比较两个字符串,以确保它们是相同的。例如,判断用户第一次与第二次输入的密码是否相同,你可以使用substr_compare()函数来很容易的现实:


$pswd = "secret";
$pswd2 = "secret";
if (! strcmp($pswd, $pswd2))
{ echo "The passwords are not identical!"; }


如果你想判断两个字符串不区分大小写,可以使用strcasecmp()函数。

9.转换换行符

在本文中我介绍了如何轻松转换成超超链接的URL,现在介绍nl2br()函数,这个函数能够帮助你将任何换行符转换成HTML标签。

$comment = nl2br($comment);

10.应用自动换行

应用自动换行,你可以使用PHP中的这个函数: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.

原文地址:http://phpbuilder.com/columns/Jason_Gilmore060210.php3
原文名:10 Easy Solutions for PHP String Manipulation
作者:W. Jason Gilmore
相关文章 大家在看